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

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

    The code below uses a random-access FileStream to seed a StreamReader at an offset near the end of the file, discarding the first read line since it is most likely only partial.

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

提交回复
热议问题