如何使用StreamReader读取特定行之后的文本文件行

时间:2014-03-14 14:43:01

标签: c# string io text-files streamreader

我有一个文本文件,我正在使用StreamReader阅读。现在根据我的要求,我先阅读的任何行,我不想再读一遍意味着我不想再拿这些数据。所以我添加了{{1代码来获取首先读取的行数。现在上面的代码行返回的任何行,我想在之后阅读。 这是我的代码。

File.ReadLines(FileToCopy).Count();

我需要在这指定什么条件。请帮助我。

        string FileToCopy = "E:\\vikas\\call.txt";

        if (System.IO.File.Exists(FileToCopy) == true)
        {

            lineCount = File.ReadLines(FileToCopy).Count();

            using (StreamReader reader = new StreamReader(FileToCopy))
            {

            }
         }

3 个答案:

答案 0 :(得分:5)

这样做的速度要快得多,并不需要您阅读整个文件才能到达上次停止的位置。关键是要跟踪文件的长度。然后将文件打开为FileStream,位置为前一个长度(即之前读取的位置),然后创建StreamReader。所以它看起来像这样:

long previousLength = 0;

然后,当你想复制新东西时:

using (var fs = File.OpenRead(FileToCopy))
{
    // position to just beyond where you read before
    fs.Position = previousLength;

    // and update the length for next time
    previousLength = fs.Length;

    // now open a StreamReader and read
    using (var sr = new StreamReader(fs))
    {
        while (!sr.EndOfStream)
        {
            var line = sr.ReadLine();
            // do something with the line
        }
    }
}

如果文件变大,这将为您节省巨大的时间。例如,如果上次读取文件时文件的大小是千兆字节,那么File.ReadLines(filename).Skip(count)将花费20秒到达结尾,以便您可以阅读下一行。我上面描述的方法将花费更少的时间 - 可能不到一秒钟。

答案 1 :(得分:1)

此:

lineCount = File.ReadLines(FileToCopy).Count();

将在文件中返回总行数。它对您无用。您需要存储从文件中读取的行数。然后每次再次阅读时,请使用Skip方法:< / p>

var nextLines = File.ReadLines("filaPath").Skip(lineCount);

您在这里不需要StreamReader。例如,如果您是第一次阅读文件,请说10行:

var lines = File.ReadLines(filePath).Take(10);
lineCount += 10;

第二次Skip第一行10行并阅读更多内容并更新lineCount

var nextLines = File.ReadLines(filePath).Skip(lineCount).Take(20);

lineCount += 20;

更一般地说,你可以为此编写一个方法,并在你想要阅读下一行时调用它:

public  static string[] ReadFromFile(string filePath, int count, ref int lineCount)
{
    lineCount += count;
    return File.ReadLines(filePath).Skip(lineCount).Take(count).ToArray();
}

private static int lineCount = 0;
private static void Main(string[] args)
{
   // read first ten line
   string[] lines = ReadFromFile("sample.txt", 10, ref lineCount);

   // read next 30 lines
   string[] otherLines = ReadFromFile("sample.txt", 30, ref lineCount)
}

我希望你明白这一点。

答案 2 :(得分:0)

只需阅读新流中的lineCount行:

for(int n=0; n<lineCount; n++) 
{
    reader.ReadLine();
}

这是最简单的方法,当你必须实际跳过N行(而不是N个字节)时。

相关问题