C sharp: read last "n" lines of log file
Posted
by
frictionlesspulley
on Stack Overflow
See other posts from Stack Overflow
or by frictionlesspulley
Published on 2011-01-06T20:53:03Z
Indexed on
2011/01/06
20:53 UTC
Read the original article
Hit count: 230
need a snippet of code which would read out last "n lines" of a log file. I came up with the following code from the net.I am kinda new to C sharp. Since the log file might be quite large, I want to avoid overhead of reading the entire file.Can someone suggest any performance enhancement. I do not really want to read each character and change position.
var reader = new StreamReader(filePath, Encoding.ASCII);
reader.BaseStream.Seek(0, SeekOrigin.End);
var count = 0;
while (count <= tailCount)
{
if (reader.BaseStream.Position <= 0) break;
reader.BaseStream.Position--;
int c = reader.Read();
if (reader.BaseStream.Position <= 0) break;
reader.BaseStream.Position--;
if (c == '\n')
{
++count;
}
}
var str = reader.ReadToEnd();
© Stack Overflow or respective owner