Read last line of text file
c#, file, file-read
Solution
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.
Problem
I need to know how to read the last line of a text file. I need to find the line and then process it into a SQL database... I've been reading around and scouring the web but am battling to find the proper way to do this. I.e.: - Find last line of file. - Process last line of file.