Reputation: 137
I am new to C#. I try to parse a text file using the StreamReader
class:
1,0
BRD1,100 - 2017.02.24-12.26 - SaraH
BRD2,HDF-101D-BL3M,2800,2070,100,0,3,HDF-101D-BL3M,,,0,,0,,
XBRD1,100 - 2017.02.24-12.26 - SaraH
XBRD2,100 - 2017.02.24-12.26 - SaraH/0001,2800,270.8,1,0,3,HDF-101D-BL3M,,,0,,1,,
PNL1,100 - 2017.02.24-12.26 - SaraH
PNL2,1,HDF-101D-BL3M,1130,295,2,0,,,,,1,0,0,PIL_100_1130x295.bmp
PRM2,21,0,50,50,0,0,0,80,80,80
PRM3,18,0,0,15,15,15,75,1,200,2,350,3,650,4,1050,5,0,6,2600,7,4200,8,0,9,0,10,0,11,0,12,0,13,0,14,0,15,0,16,0,17,0,18
MAT2,HDF-101D-BL3M,HDF 101D white h-3mm,3,0,2,4.8,4.8,4.8,0,0,0,15,15,15,15,5,5,5,0,250,250,0.06,0,60,2200,0,0,0,0,0,1,1,0,0,0,2,0,0,0,1,30,30,30,17,NTMDPI,0,19,9.51,0.03,2,11.59,0.03,2,2,0,0:11,,,,,,,,,,RGB(255:255:255),
PTN2,1,,1,1,4:38,0:04,5,11,0,0
PTNR,(((5!),X2),((7!),(9),(9),(9)),(3!,2!))
INFO1,100 - 2017.02.24-12.26 - SaraH,100 - 2017.02.24-12.26 - SaraH,standart15,HP30
INFO4,2
CHK1,9183
I need to get a string there is after BRD1, MAT2, INFO4
also
100 - 2017.02.24-12.26 - SaraH --> to label1
HDF-101D-BL3M,HDF 101D white-3mm --> to label2
2 --> to label3
At the moment, I try to choose only the right lines and then split.
Because if (line.Contains(word))
choose all lines which contain this string, I need something like line.BeginWith(word)
.
Also, if someone can help me, or can introduce me, if there is a better way to get this result.
private void OnChanged(object source, FileSystemEventArgs e)
{
string line;
string[] words = { "BRD1", "MAT2", "INFO4"};
// Read the file and display it line by line.
using (var file = new System.IO.StreamReader(e.FullPath))
{
while ((line = file.ReadLine()) != null)
{
foreach (string word in words)
{
if (line.Contains(word))
{
string[] fields = line.Split(',');
}
}
}
}
}
Upvotes: 1
Views: 500
Reputation: 237
It would be a much more efficient way using regular expressions to parse the full text at once.
List<string> labels = new List<string>();
Regex regex = new Regex(@"\r\n(BRD1|MAT2|INFO4),([^(,|\r\n)]*,?[^(,|\r\n)]*)");
using (var file = new System.IO.StreamReader(e.FullPath))
{
foreach (Match match in regex.Matches(file.ReadToEnd()))
{
labels.Add(match.Groups[2].Value);
}
}
Upvotes: 1
Reputation: 14017
You can use String.StartsWith
:
foreach (string word in words)
{
if (line.StartsWith(word))
{
string[] fields = line.Split(',');
}
}
As an additional simplification, you can avoid the forach
loop with the LINQ method Enumerable.Any
:
if (words.Any(word => line.StartsWith(word)))
{
string[] fields = line.Split(',');
}
Upvotes: 1