19

我是 C# 新手,我已经开始使用StreamReader. 我试图一次读取一行文件,并在它与特定关键字(如“I/RPTGEN”)匹配时输出该行。

到目前为止,我想出了如何将整个文件读入一个字符串,但我无法弄清楚如何一次只读取一行。

到目前为止,我的代码是这样的。

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication5
{
class Test
{
    public static void Main()
    {
        try
        {
            using (StreamReader sr = new StreamReader("c:/temp/ESMDLOG.csv"))
            {
                String line = sr.ReadToEnd();
                Console.WriteLine(line);

                Console.ReadLine();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The File could not be read:");
            Console.WriteLine(e.Message);

            Console.ReadLine();
        }
    }
}
}

另外,这里是文件中一行的示例。

咨询,2013 年 2 月 27 日上午 12:00:44,I/RPTGEN(cadinterface),I/RPTGEN 失败 - 错误 500 - 内部服务器错误 - 返回报告请求(检查 URL 日志)。

4

2 回答 2

38

如果您的 CSV 文件仅包含一行,则ReadToEnd可以接受,但如果您的日志文件由多行组成,则最好使用ReadLine对象StreamReader逐行读取

using (StreamReader sr = new StreamReader("c:/temp/ESMDLOG.csv"))
{
    string currentLine;
    // currentLine will be null when the StreamReader reaches the end of file
    while((currentLine = sr.ReadLine()) != null)
    {
       // Search, case insensitive, if the currentLine contains the searched keyword
       if(currentLine.IndexOf("I/RPTGEN", StringComparison.CurrentCultureIgnoreCase) >= 0)
       {
            Console.WriteLine(currentLine);
       }
    }
}
于 2013-03-21T23:29:47.003 回答
12

另一种一次读取一行的方法是:

var searchItem = "Error 500";

var lines = File.ReadLines("c:/temp/ESMDLOG.csv");

foreach (string line in lines)
{
    if (line.Contains(searchItem))
    {
        Console.WriteLine(line);
    }
}
于 2013-03-22T00:31:39.203 回答