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

前端 未结 4 814
长情又很酷
长情又很酷 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:58

    To read the last 1024 bytes:

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

提交回复
热议问题