-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileReader.cs
85 lines (81 loc) · 2.68 KB
/
FileReader.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace gtkfetch
{
public class FileReader
{
/// <summary> Returns first match </summary>
public static string ReadFileAndFindGroup(string path, string regex, int group)
{
try
{
using (StreamReader file = new StreamReader(path))
{
string line;
while ((line = file.ReadLine()) != null)
{
if (Regex.IsMatch(line, regex))
{
Match m = Regex.Match(line, regex);
return m.Groups[group].Value.ToString();
}
}
}
}
catch (Exception e)
{
Console.WriteLine($"something broke: {e}");
return null;
}
return null;
}
/// <summary> Reads file and regex matches things on all lines of the file </summary>
public static List<string> ReadFileMatchMultiple(string path, string regex, int group)
{
List<string> matches = new List<string>();
try
{
using (StreamReader file = new StreamReader(path))
{
string line;
while ((line = file.ReadLine()) != null)
{
if (Regex.IsMatch(line, regex))
{
Match m = Regex.Match(line, regex);
// check if the group even exists, and also checks if its not an empty match
if (m.Groups[1] != null && m.Groups[1].Value != "")
{
matches.Add(m.Groups[group].Value.ToString());
}
}
}
return matches;
}
}
catch (Exception e)
{
Console.WriteLine($"something broke: {e}");
return null;
}
}
/// <summary> Reads single line of file </summary>
public static string ReadLine(string path)
{
try
{
using (StreamReader file = new StreamReader(path))
{
return file.ReadLine();
}
}
catch (Exception e)
{
Console.WriteLine($"something broke: {e}");
return null;
}
}
}
}