我必须逐行阅读日志文件。它的大小约为 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/