只需要从大日志文件中获取最后一行。最好的方法是什么?
您想使用 ReverseLineReader
向后读取文件:
如何在 C# 中使用迭代器反向读取文本文件
然后在它上运行.Take(1)
。
var lines = new ReverseLineReader(filename);
var last = lines.Take(1);
您需要直接使用 Jon Skeet 的库 MiscUtil,而不是复制/粘贴代码。
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;
}
或者
你可以做两行(仅限.Net 4)
var lines = File.ReadLines(path);
string line = lines.Last();