Read only last lines of x in txt file

I am currently reading the contents of a file using File.ReadAllText (), but now I need to read the last lines of x in my txt file. How can i do this?

the contents of myfile.txt

 line1content line2content line3content line4content string contentOfLastTwoLines = ... 
+4
source share
6 answers

How about this

 List <string> text = File.ReadLines("file.txt").Reverse().Take(2).ToList() 
+7
source

Use Queue<string> to store the last lines of X and replace the first one that is currently read:

 int x = 4; // number of lines you want to get var buffor = new Queue<string>(x); var file = new StreamReader("Input.txt"); while (!file.EndOfStream) { string line = file.ReadLine(); if (buffor.Count >= x) buffor.Dequeue(); buffor.Enqueue(line); } string[] lastLines = buffor.ToArray(); string contentOfLastLines = String.Join(Environment.NewLine, lastLines); 
+5
source

Read the lines in the array, then extract the last two:

 string[] lines = File.ReadAllLines(); string last2 = lines[lines.Count-2] + Environment.NewLine + lines[lines.Count-1]; 

Assuming your file is small enough, it's easier to just read it all and throw away what you don't need.

+3
source

You can use ReadLines to not read the entire file in memory, for example:

 const int neededLines = 5; var lines = new List<String>(); foreach (var s in File.ReadLines("c:\\myfile.txt")) { lines.Add(s); if (lines.Count > neededLines) { lines.RemoveAt(0); } } 

As soon as the for loop is completed, the lines list contains up to the last neededLines text from the file. Of course, if the file does not contain as many lines as required, fewer lines will be placed in the lines list.

+3
source

Since reading the file is linear, usually line by line. Just read line by line and remember the last two lines (you can use a queue or something if you want ... or just two string variables). When you get to EOF, you will have the last two lines.

0
source

You want to read the file back with ReverseLineReader:

How to read a text file using an iterator in C #

Then run .Take (2). var lines = new ReverseLineReader (file name); var last = lines.Take (2);

OR

Use System.IO.StreamReader.

 string line1, line2; using(StreamReader reader = new StreamReader("myFile.txt")) { line1 = reader.ReadLine(); line2 = reader.ReadLine(); } 
0
source

All Articles