需要从大日志文件中获取最后一行。最好的方法是什么?
问问题
21583 次
3 回答
14
您想使用以下方式向后读取文件ReverseLineReader
:
然后.Take(1)
在上面运行。
var lines = new ReverseLineReader(filename);
var last = lines.Take(1);
您需要直接使用Jon Skeet 的库MiscUtil,而不是复制/粘贴代码。
于 2012-05-02T08:13:47.840 回答
2
String lastline="";
String filedata;
// Open file to read
var fullfiledata = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader sr = new StreamReader(fullfiledata);
//long offset = sr.BaseStream.Length - ((sr.BaseStream.Length * lengthWeNeed) / 100);
// Assuming a line doesnt have more than 500 characters, else use above formula
long offset = sr.BaseStream.Length - 500;
//directly move the last 500th position
sr.BaseStream.Seek(offset, SeekOrigin.Begin);
//From there read lines, not whole file
while (!sr.EndOfStream)
{
filedata = sr.ReadLine();
// Interate to see last line
if (sr.Peek() == -1)
{
lastline = filedata;
}
}
return lastline;
}
于 2014-11-22T23:46:08.587 回答
-2
或者你可以做两行(仅限.Net 4)
var lines = File.ReadLines(path);
string line = lines.Last();
于 2012-05-18T17:24:44.583 回答