3

At the moment I have a file being read for a specific entry "X". Once I find this entry I can do what I need to do in any following lines BUT there is a piece of information that is required 2 lines before the "X" appears. Right now I am able to use var line = reader.ReadLine(); to move forward in the file and read lines that come after "X". How do I move back to read that data 2 lines before?

while (!reader.EndOfStream)
{
    var line = reader.ReadLine();

    if (line.Contains("X"))
    {
        Processing
    }
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
user001
  • 415
  • 1
  • 7
  • 22

5 Answers5

10

Save it as you go along:

string prev1;
string prev2;

while (!reader.EndOfStream)
{

    var line = reader.ReadLine();

    if (line.Contains("X"))
    {
        Processing
    }

    prev2 = prev1;
    prev1 = line;
}

If you need more than this it could easily be converted into a queue that you push/pull from.

Jon Egerton
  • 40,401
  • 11
  • 97
  • 129
  • If I do that have I set the line to be ahead of the line containing "X" again? Would I need to bring the line back below "X" to prevent it being read again? – user001 Aug 06 '15 at 10:56
  • 1
    @user2399216: No - the actual file read itself is un affected, you're just caching previously read lines into memory as you go along. – Jon Egerton Aug 06 '15 at 10:58
  • It's breaking the loop. I need to continue checking the document for "X" as it is a Marker for unique results being presented. "X" will appear several times and its unique surrounding data will need to be collected each time – user001 Aug 06 '15 at 11:23
  • @user2399216: The looping style given would do that for each occurence of 'X' (ie capture the 2 rows prior to the row that contains X). – Jon Egerton Aug 06 '15 at 11:32
4

Instead of StreamReader you can use File.ReadAllLines which returns a string array:

string[] lines = File.ReadAllLines("file.txt")
for (int i = 0; i < lines.Length; i++)
{
    if (lines[i].Contains("X") && i >= 2)
    {
         string res = lines[i-2];
    } 
}
w.b
  • 11,026
  • 5
  • 30
  • 49
0

Just store the last 2 lines read.

Fixed size queue which automatically dequeues old values upon new enques

Community
  • 1
  • 1
Mark Jansen
  • 1,491
  • 12
  • 24
0

Store the 2 previous lines :

string [] lineprev = new string[]{"",""} ;
while (!reader.EndOfStream)
{
    var line = reader.ReadLine();
    if (line.Contains("X"))
    {
        // Processing : Find info in lineprev[1]
    }
    lineprev[1]=lineprev[0] ;
    lineprev[0]= line ;
}
Graffito
  • 1,658
  • 1
  • 11
  • 10
-1

Try to keep previous line in memory, so you can access it, when you need. Something like this:

var prev;
while (!reader.EndOfStream)
{
    var line = reader.ReadLine();

    if (line.Contains("X")) {
        // Processing both line and prev
    }

    prev = line; // remember previous line for future use
}