• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 209
  • Last Modified:

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
0
NewMom2Brandon
Asked:
NewMom2Brandon
  • 3
  • 2
1 Solution
 
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
 
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
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

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now