4

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

内容myfile.txt

line1content 
line2content
line3content
line4content 

string contentOfLastTwoLines = ...
4

6 回答 6

10

What about this

List <string> text = File.ReadLines("file.txt").Reverse().Take(2).ToList()
于 2013-04-07T21:09:58.937 回答
5

用于Queue<string>存储最后X一行并将第一行替换为当前读取的:

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);
于 2013-04-07T21:07:26.610 回答
4

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

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

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.

于 2013-04-07T21:08:34.963 回答
3

将这些行读入一个数组,然后提取最后两个:

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

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

于 2013-04-07T21:04:02.733 回答
0

由于读取文件是线性完成的,通常是逐行完成的。只需逐行阅读并记住最后两行(如果需要,您可以使用队列或其他东西......或者只是两个字符串变量)。当您到达 EOF 时,您将获得最后两行。

于 2013-04-07T21:03:56.493 回答
0

You want to read the file backwards using ReverseLineReader:

How to read a text file reversely with iterator in C#

Then run .Take(2) on it. var lines = new ReverseLineReader(filename); var last = lines.Take(2);

OR

Use a System.IO.StreamReader.

string line1, line2;

using(StreamReader reader = new StreamReader("myFile.txt")) {
    line1 = reader.ReadLine();
    line2 = reader.ReadLine();
}
于 2013-04-07T21:08:46.953 回答