Search code examples
c#text-filesstreamreader

Read a preceding line of a text file; if current line contains "X"


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
    }
}

Solution

  • 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];
        } 
    }