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

标签 c# file streamreader

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

我该如何解决这个问题?

编辑:我尝试使用文本阅读器,但我的程序仍然无法运行:

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

最佳答案

TextReader.ReadLine 已经处理了由 \n 终止的行。

来自 the docs :

A line is defined as a sequence of characters followed by a carriage return (0x000d), a line feed (0x000a), a carriage return followed by a line feed, Environment.NewLine, or the end of stream marker. The string that is returned does not contain the terminating carriage return and/or line feed. The returned value is a null reference (Nothing in Visual Basic) if the end of the input stream has been reached.

所以基本上,你应该没问题。 (我谈论的是 TextReader 而不是 StreamReader 因为这是声明方法的地方 - 显然它仍然可以与 StreamReader 一起工作。)

如果您想轻松地遍历行(并可能对日志文件使用 LINQ),您可以在 MiscUtil 中找到我的 LineReader 类有用。它基本上将对 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)
{
    // ...
}

所有流媒体:)

关于c# - 如何读取仅由 LF 分隔的文件中的每一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1142043/

相关文章:

c# - 复选框中的绑定(bind)与命令

c# - 声明一个一次性对象 : inside or outside a loop?

python - 从文本文件中删除字符串保持 float

python - 将搜索添加到文件类型对象的廉价方法

.net - RichTextBox 不显示 ' 并显示一个菱形,而不是里面有一个问号

c# - 如何让文本框删除以阿拉伯字符(半彼此)开头的字符串,就像默认语言中的大写字符和小字符一样?

c# - 使用嵌套 for 循环将 Lambda 转换为 Linq 语句

iOS 应用内购买 : hosted contents size limits?

c# - 创建文件后发生文件共享冲突?

c# - 如何将 Windows 窗体 GUI 中字段的值保存到文件,然后恢复它们?