Need to pull Line before string found in Text file

Ok I have a text file which is being searched by a windows service. It finds the string fine. What I need to do is as soon as it finds the string...it needs to pull the line before it and compare it to todays date.

What I am looking for is how to get the line before the string I was looking for

EXAMPLE:
Text file

May 2, 2005 10:38 AM
LINE I WAS SEARCHING FOR
LVL 2
NewMom2BrandonAsked:
Who is Participating?
 
BurntSkyCommented:
When currentLine becomes equal to "LINE I WAS SEARCHING FOR" the loop will exit and currentLine will still retain its value.

The code I posted is just an example of a way to do what you need.  I wouldn't expect you to use it line-for-line.
0
 
BurntSkyCommented:
just cache the line before:

            using (StreamReader sr = new StreamReader("test.txt"))
            {
                string currentLine = sr.ReadLine();
                string previousLine;
                while (currentLine != null && currentLine != "LINE I WAS SEARCHING FOR")
                {
                    previousLine = currentLine;
                    currentLine = sr.ReadLine();
                }
            }
0
 
NewMom2BrandonAuthor Commented:
I still need to use the line I was searching for too though.

The line before is just needed for a date comparison
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
Carl TawnSystems and Integration DeveloperCommented:
The code that BurntSky posted will do that for you. previousLine will always hold the line read previously and currentLine will hold the current line.
So, from your example, when the loop exits you will have:

    previousLine == "May 2, 2005 10:38 AM"
    currentLine == "LINE I WAS SEARCHING FOR"
0
 
NewMom2BrandonAuthor Commented:
Thank you ...you guys beat me to the reply. I modified the code a bit and it works great...thank you!!!
0
 
BurntSkyCommented:
Good.  Glad I could help =)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.