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.:
var lastLine = File. ReadLines("file. txt"). Last();
tail works the same way as head: type tail and the filename to see the last 10 lines of that file, or type tail -number filename to see the last number lines of the file.
This snippet should work for you: BufferedReader input = new BufferedReader(new FileReader(fileName)); String last, line; while ((line = input. readLine()) != null) { last = line; } //do something with last!
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.
I would simply combine File.ReadLines(path)
and Enumerable.Last
:
String last = File.ReadLines(@"C:\file.txt").Last();
It streams the lines and does not load all into memory as File.ReadAllLines
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With