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

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

    Take a look at this related question's answer to read a text file in reverse. There is a lot of complexity to reading a file backward correctly because of stuff like encoding.

    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 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);
        }
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题