如何读取仅由LF分隔的文件中的每一行?

Vim*_*987 2 c# file streamreader

我必须逐行读取日志文件.它的大小约为6MB,总线数为40000.但在测试我的程序后,我发现该日志文件仅由LF字符分隔.所以我不能使用类的Readline方法StreamReader

我该如何解决这个问题?

编辑:我尝试使用文本阅读器,但我的程序仍然无法正常工作:

using (TextReader sr = new StreamReader(strPath, Encoding.Unicode))
            {


                sr.ReadLine(); //ignore three first lines of log file
                sr.ReadLine(); 
                sr.ReadLine();

                int count = 0; //number of read line
                string strLine;
                while (sr.Peek()!=0)
                {
                    strLine = sr.ReadLine();
                    if (strLine.Trim() != "")
                    {
                        InsertData(strLine);
                        count++;
                    }
                }

                return count;
            }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 9

TextReader.ReadLine已处理仅由终止的行\n.

来自文档:

行被定义为字符序列,后跟回车符(0x000d),换行符(0x000a),回车符后跟换行符,Environment.NewLine或流结束标记符.返回的字符串不包含终止回车符和/或换行符.如果已到达输入流的末尾,则返回的值为空引用(在Visual Basic中为Nothing).

所以基本上,你应该没事.(我已经谈过TextReader而不是StreamReader因为那是声明方法的地方 - 显然它仍然适用于StreamReader.)

如果你想轻松地遍历行(并且可能对日志文件使用LINQ),你可能会发现我LineReaderMiscUtil中的类很有用.它基本上包含ReadLine()了迭代器中的调用.例如,您可以这样做:

var query = from file in Directory.GetFiles("logs")
            from line in new LineReader(file)
            where !line.StartsWith("DEBUG")
            select line;

foreach (string line in query)
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

所有流媒体:)