Reputation: 177
i have created a log file example.txt that records events as
Button1 Click event happen ID=xyz DT:3/1/2015 9:27:32 AM
Button2 Click event happen ID=xyz DT:3/1/2015 9:28:32 AM
Button1 Click event happen ID=xyz DT:3/1/2015 9:29:32 AM
Button2 Click event happen ID=xyz DT:3/1/2015 9:30:32 AM
i can read those file but i will get everything written in the log file.\ i have used the following code
try
{
using(FileStream fileStream = new FileStream("c://temp1/example_logfile.txt",FileMode.Open,FileAccess.Read,FileShare.ReadWrite))
{
using(StreamReader streamReader = new StreamReader(fileStream))
{
this.txt.Text = streamReader.ReadToEnd();
}
}
}
I want to read just the Button1 click event. how do you do that?
Upvotes: 2
Views: 13767
Reputation: 13069
What about a solution with StreamReader.ReadLine()
combined with String.Contains()
String line;
while (!streamReader.EndOfStream) // <= Check for end of file
{
line = streamReader.ReadLine(); // <=Get a single line
if (line.Contains("Button1")) // <= Check for condition ; line contains 'Button1'
{
this.txt.Text += line + "\n"; // <== Append text with a newline
}
}
Upvotes: 3
Reputation: 66459
Use File.ReadLines
and a bit of LINQ to get only the lines you're interested in:
var results = File.ReadLines(filePath).Where(x => x.StartsWith("Button1 Click"));
Now you've got a collection of strings representing the matching lines. If you want to display them in a single TextBox
, you can flatten the list back out to a single string:
this.txt.Text = String.Join(", ", results);
Or modify the LINQ statement to get, say, the first match only: (assuming at least one match)
this.txt.Text = File.ReadLines(filePath).First(x => x.StartsWith("Button1 Click"));
Upvotes: 4