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.
source share