Read the previous line of the text file; if the current line contains "X",

At this point I have a file that is being read for a specific record "X". Once I find this entry, I can do what I need to do on the following lines, but there is some information that takes 2 lines before the "X" appears. Right now I can use var line = reader.ReadLine();

to move forward in the file and read the lines that appear after the "X". How do I go back to read this data 2 lines earlier?

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

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

      

+3


source to share


5 answers


Instead, 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];
    } 
}

      

+3


source


Save it as you go:

string prev1;
string prev2;

while (!reader.EndOfStream)
{

    var line = reader.ReadLine();

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

    prev2 = prev1;
    prev1 = line;
}

      



If you need more this can easily be converted to a queue you push / pull on.

+10


source


0


source


Save the previous two 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 ;
}

      

0


source


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

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
}

      

-1


source







All Articles