Need to get just last line from big log file. What is the best way to do that?
Asked
Active
Viewed 2.3k times
3 Answers
14
You want to read the file backwards using ReverseLineReader
:
How to read a text file reversely with iterator in C#
Then run .Take(1)
on it.
var lines = new ReverseLineReader(filename);
var last = lines.Take(1);
You'll want to use Jon Skeet's library MiscUtil directly rather than copying/pasting the code.
-
Nice! Thank you, will try it. – 0x49D1 May 02 '12 at 08:14
-
1Strange that the library is not in Nuget..Thanks! – 0x49D1 May 02 '12 at 08:17
-
See my answer in the possible duplicate http://stackoverflow.com/a/33907602/4821032 – Xan-Kun Clark-Davis Nov 25 '15 at 02:42
-
1I know this answer is from the past, but for anyone reading this, "You'll want to NOT use Jon Skeet's library directly" as per Jon Skeet himself, rather DO copy/paste, take what you want from the code. https://github.com/jpsingleton/ANCLAFS/issues/6 – joedotnot Feb 27 '21 at 02:38
2
String lastline="";
String filedata;
// Open file to read
var fullfiledata = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader sr = new StreamReader(fullfiledata);
//long offset = sr.BaseStream.Length - ((sr.BaseStream.Length * lengthWeNeed) / 100);
// Assuming a line doesnt have more than 500 characters, else use above formula
long offset = sr.BaseStream.Length - 500;
//directly move the last 500th position
sr.BaseStream.Seek(offset, SeekOrigin.Begin);
//From there read lines, not whole file
while (!sr.EndOfStream)
{
filedata = sr.ReadLine();
// Interate to see last line
if (sr.Peek() == -1)
{
lastline = filedata;
}
}
return lastline;
}

Jagadheesh
- 21
- 1
-2
Or you can do it two line (.Net 4 only)
var lines = File.ReadLines(path);
string line = lines.Last();

RedFox
- 1,158
- 2
- 15
- 28
-
While this can do the job, it's incredibly memory inefficient (as RJFalconer notes) and also has a great deal of latency - remember that reading a file is one of the slowest things you can do in a program. If you're only infrequently reading, this might work out, but this is _far_ from a strong, professional solution. – Andrew Gray Sep 18 '17 at 17:08