5

Is there a function in the streamreader that allows for peek/read the next line to get more information without actually moving the iterator to the next position?

The action on the current line depends on the next line, but I want to keep the integrity of using this code block

while((Line = sr.ReadLine())!=null)
tshepang
  • 12,111
  • 21
  • 91
  • 136
Yang
  • 6,682
  • 20
  • 64
  • 96
  • 6
    Is there any reason not to read the entire file into memory and work with it there? Is the size prohibitively large? – Yuck Dec 03 '13 at 19:40
  • 1
    @Yuck, right, the file is too large to be loaded into the memory – Yang Dec 03 '13 at 19:42
  • 1
    How about having code that works by reading two lines at a time? Do you need to know whats only in the next line or further more? – rageit Dec 03 '13 at 19:45

1 Answers1

10

In principle, there is no need to do such a thing. If you want to relate two consecutive lines, just adapt the analysis to this fact (perform the line 1 actions while reading line 2). Sample code:

using (System.IO.StreamReader sr = new System.IO.StreamReader("path"))
{
    string line = null;
    string prevLine = null;
    while ((line = sr.ReadLine()) != null)
    {
        if (prevLine != null)
        {
            //perform all the actions you wish with the previous line now
        }

        prevLine = line;
    }
}

This might be adapted to deal with as many lines as required (a collection of previous lines instead of just prevLine).

varocarbas
  • 12,354
  • 4
  • 26
  • 37
  • Thanks. I'm currently using exactly the same way as yours (even the variable name is accidentally the same as well :)), just wondering if there are other better approaches. – Yang Dec 03 '13 at 19:49
  • 2
    @Yang (I chose a good name then :)) if something works fine, why changing it? I have used this kind of approaches a lot and never had a problem: it is reliable, clear and quick. – varocarbas Dec 03 '13 at 19:51
  • 1
    @Yang I second that. I would speculate this is the most common approach. In fact, I spent several minutes searching for some reasonable way of doing it using a `StreamReader` method and couldn't find anything useful. – evanmcdonnal Dec 03 '13 at 20:14