Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read last line of text file

Tags:

c#

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.:

  1. Find last line of file.
  2. Process last line of file.
like image 443
Debbie Dippenaar Avatar asked Jul 24 '12 06:07

Debbie Dippenaar


People also ask

How do I read the last line of a text file?

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

How do I get the last line of a file?

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.

How do you read the last line of a file in Java?

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!


2 Answers

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.

like image 104
Jon Skeet Avatar answered Sep 20 '22 00:09

Jon Skeet


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.

like image 42
Tim Schmelter Avatar answered Sep 19 '22 00:09

Tim Schmelter