Read from a file starting at the end, similar to tail

前端 未结 4 808
长情又很酷
长情又很酷 2020-11-28 10:25

In native C#, how can I read from the end of a file?

This is pertinent because I need to read a log file, and it doesn\'t make sense to read 10k, to read the last

4条回答
  •  孤城傲影
    2020-11-28 10:59

    Maybe something like this will work for you:

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

    Take note that this assumes \r\n.

提交回复
热议问题