Read last line of text file

There are two ways: simple and inefficient, or horrendously complicated but efficient. The complicated version assumes a sane encoding.

Unless your file is so big that you really can’t afford to read it all, I’d just use:

var lastLine = File.ReadLines("file.txt").Last();

Note that this uses File.ReadLines, not File.ReadAllLines. If you’re using .NET 3.5 or earlier you’d need to use File.ReadAllLines or write your own code – ReadAllLines will read the whole file into memory in one go, whereas ReadLines streams it.

Otherwise, the complicated way is to use code similar to this. It tries to read backwards from the end of the file, handling nastiness such as UTF-8 multi-byte characters. It’s not pleasant.

Leave a Comment