在C#中,如何从文件末尾读取内容?
这很重要,因为我需要读取日志文件,而读取最后3行不必读取10k行。
读取最后的1024个字节:
using (var reader = new StreamReader("foo.txt"))
{
if (reader.BaseStream.Length > 1024)
{
reader.BaseStream.Seek(-1024, SeekOrigin.End);
}
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
using (var fs = File.OpenRead(filePath))
{
fs.Seek(0, SeekOrigin.End);
int newLines = 0;
while (newLines < 3)
{
fs.Seek(-1, SeekOrigin.Current);
newLines += fs.ReadByte() == 13 ? 1 : 0; // look for \r
fs.Seek(-1, SeekOrigin.Current);
}
byte[] data = new byte[fs.Length - fs.Position];
fs.Read(data, 0, data.Length);
}
请注意,这假定为 \r\n
。
FileStream
在接近文件结尾的偏移量处为 StreamReader
提供种子,丢弃第一个读取的行,因为它很可能只是部分内容。FileStream stream = new FileStream(@"c:\temp\build.txt",
FileMode.Open, FileAccess.Read);
stream.Seek(-1024, SeekOrigin.End); // rewind enough for > 1 line
StreamReader reader = new StreamReader(stream);
reader.ReadLine(); // discard partial line
while (!reader.EndOfStream)
{
string nextLine = reader.ReadLine();
Console.WriteLine(nextLine);
}
查看这个相关问题的答案,以反向读取文本文件。由于编码等原因,正确地反向读取文件非常复杂。