只读给定txt文件中的最后x行

目前我正在使用File.ReadAllText()读取文件内容,但现在我需要读取我的txt文件中的最后x行。 我怎样才能做到这一点?

myfile.txt内容

 line1content line2content line3content line4content string contentOfLastTwoLines = ... 

那这个呢

 List  text = File.ReadLines("file.txt").Reverse().Take(2).ToList() 

使用Queue存储最后的X行,并用当前读取的第一行代替:

 int x = 4; // number of lines you want to get var buffor = new Queue(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); 

您可以使用ReadLines来避免将整个文件读入内存,如下所示:

 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); } } 

for循环完成后, lines列表最多包含文件中最后一个neededLines的文本行。 当然,如果文件不包含所需的行数,则lines列表中将放置更少的lines

将行读入数组,然后提取最后两行:

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

假设您的文件相当小,那么只需阅读整个内容并丢弃您不需要的文件就更容易了。

由于读取文件是线性完成的,因此通常是逐行完成的。 只需逐行读取并记住最后两行(如果需要,可以使用队列或其他内容……或只使用两个字符串变量)。 当你到达EOF时,你将拥有最后两行。

您想使用ReverseLineReader向后读取文件:

如何在C#中使用迭代器反向读取文本文件

然后跑。拿它(2)就可以了。 var lines = new ReverseLineReader(filename); var last = lines.Take(2);

要么

使用System.IO.StreamReader。

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