Reading the next line of a file only once

。_饼干妹妹 提交于 2019-12-04 14:01:57

Simply use

 string[] lines = File.ReadAllLines(filename);

and process the file with a for (int i = 0; i < lines.Length; i ++) loop.

For a big file, simply cache the 'previous line' or do an out-of-band ReadLine().

Here is an idiom to process the current line you while having the next line already available:

public void ProcessFile(string filename)
{
    string line = null;
    string nextLine = null;
    using (StreamReader reader = new StreamReader(filename))
    {
        line = reader.ReadLine();
        nextLine = reader.ReadLine();
        while (line != null)
        {
            // Process line (possibly using nextLine).

            line = nextLine;
            nextLine = reader.ReadLine();
        }
    }
}

This is basically a queue with a maximum of two items in it, or "one line read-ahead".

Edit: Simplified.

Can you not just call reader.ReadLine() again? Or is the problem that you then need to use the line in the next iteration of the loop?

If it's a reasonably small file, have you considered reading the whole file using File.ReadAllLines()? That would probably make it simpler, although obviously a little less clean in other ways, and more memory-hungry for large files.

EDIT: Here's some code as an alternative:

using (TextReader reader = File.OpenText(filename))
{
    string line = null; // Need to read to start with

    while (true)
    {
        if (line == null)
        {
            line = reader.ReadLine();
            // Check for end of file...
            if (line == null)
            {
                break;
            }
        }
        if (line.Contains("Magic category"))
        {
            string lastLine = line;
            line = reader.ReadLine(); // Won't read again next iteration
        }
        else
        {
            // Process line as normal...
            line = null; // Need to read again next time
        }
    }
}

You could save the position of the stream then after calling ReadLine, seek back to that position. However this is pretty inefficient.

I would store the result of ReadLine into a "buffer", and when possible use that buffer as a source. When it is empty, use ReadLine.

I am not really a file IO expert... but why not do something like this:

Before you start reading lines declare two variables.

string currentLine = string.Empty
string previousLine = string.Empty

Then while you are reading...

previousLine = currentLine;
currentLine = reader.ReadLine();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!