Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

file-io

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 3 lines.

like image 956
C. Ross Avatar asked Dec 06 '10 16:12

C. Ross


2 Answers

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);     } } 
like image 200
Darin Dimitrov Avatar answered Sep 23 '22 21:09

Darin Dimitrov


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.

like image 42
ChaosPandion Avatar answered Sep 22 '22 21:09

ChaosPandion