You can use ReadLines
to avoid reading the entire file into memory, like this:
const int neededLines = 5;
var lines = new List();
foreach (var s in File.ReadLines("c:\\myfile.txt")) {
lines.Add(s);
if (lines.Count > neededLines) {
lines.RemoveAt(0);
}
}
Once the for
loop is finished, the lines
list contains up to the last neededLines
of 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.