Reputation: 219
I am attempting to parse a text file and have encountered a problem. I needed to read a line after the word "MESSAGE".
The file would contain sample data like the following.
MESSAGE
2005 Repair auto axle driver side.
MESSAGE
1508 Repair hydrolic suspension.
In this case I wanted to read the lines beginning with 2005 and 1508.
Here is my code
List<Record> records = new List<Record>();
using (FileStream fs = new FileStream("SampleData.txt", FileMode.Open))
{
using (StreamReader rdr = new StreamReader(fs))
{
string tempreadline;
tempreadline = rdr.ReadLine();
while (tempreadline != null)
{
if (tempreadline.Contains("MESSAGE")
{
// what do I do here?
// skip "MESSAGE" line and read the next line
}
}
}
}
Any suggestions? Thank you!
Upvotes: 1
Views: 2325
Reputation: 16917
METHOD 1
Using your approach.
Console.WriteLine("METHOD 1");
var records = new List<string>();
using (var fs = new FileStream("d:\\SampleData.txt", FileMode.Open))
{
using (var rdr = new StreamReader(fs))
{
var msgFound = false;
while (!rdr.EndOfStream)
{
var tempreadline = rdr.ReadLine();
if (tempreadline.Contains("MESSAGE"))
{
msgFound = true;
}
else if (msgFound && !string.IsNullOrEmpty(tempreadline))
{
records.Add(tempreadline);
msgFound = false;
}
}
}
}
records.ForEach(r => Console.WriteLine(r));
METHOD 2
Assuming your text is a single string.
Console.WriteLine("METHOD 2");
var text = File.ReadAllText("d:\\SampleData.txt");
records = text.Split(new[] { "MESSAGE" }, StringSplitOptions.RemoveEmptyEntries)
.Select(t => t.Trim(' ', '\r', '\n'))
.Where(t => !string.IsNullOrEmpty(t))
.ToList();
records.ForEach(r => Console.WriteLine(r));
METHOD 3
Assuming your text is a list of strings.
Console.WriteLine("METHOD 3");
var texts = File.ReadLines("d:\\SampleData.txt");
records = texts.Where(t => !string.IsNullOrEmpty(t) && !t.StartsWith("MESSAGE"))
.ToList();
records.ForEach(r => Console.WriteLine(r));
METHOD 4
Using regular expressions.
Console.WriteLine("METHOD 4");
records = new Regex(@"^MESSAGE[\s]*$", RegexOptions.IgnoreCase | RegexOptions.Multiline)
.Split(text)
.Select(t => t.Trim(' ', '\r', '\n'))
.Where(t => !string.IsNullOrEmpty(t))
.ToList();
records.ForEach(r => Console.WriteLine(r));
Upvotes: 3
Reputation: 17605
If the desired content is in a file, you could use a combination of the File.ReadAllLines
method, which is described here, and a Linq extension method, as follows. The array DesiredLines
can the be processed further.
var DesiredLines = File.ReadAllLines("C:\FileName.txt")
.Where( iLine => iLine != "MESSAGE" && iLine != "")
.ToArray();
Upvotes: 0