使用c#读取和查询txt /日志文件

时间:2015-02-28 04:59:54

标签: c#

我创建了一个将事件记录为

的日志文件example.txt
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

我可以读取这些文件,但我会将所有内容写入日志文件中。 我使用了以下代码

    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();
            }
        }
     }

我想只阅读Button1点击事件。你是怎样做的?

2 个答案:

答案 0 :(得分:4)

使用File.ReadLines和一些LINQ来获取您感兴趣的行:

var results = File.ReadLines(filePath).Where(x => x.StartsWith("Button1 Click"));

现在你有一组表示匹配线的字符串。如果要在单个TextBox中显示它们,可以将列表展平为单个字符串:

this.txt.Text = String.Join(", ", results);

或者修改LINQ语句以获得第一场比赛:(假设至少有一场比赛)

this.txt.Text = File.ReadLines(filePath).First(x => x.StartsWith("Button1 Click"));

答案 1 :(得分:2)

StreamReader.ReadLine()结合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 
        } 
     }