Bari
Bari

Reputation: 75

Moving in text file with C#

I have a problem with C#.

I am writing code to search a text file until it finds a certain word, then the code should move three lines and read the fourth, then continue the search to find the certain word again. Now I don't know how to navigate through the file (forward and backward) to the line I want.

Can anybody help?

Upvotes: 0

Views: 541

Answers (3)

JDennis
JDennis

Reputation: 682

Your requirements state that you are searching for a specific word. If that is true and you are not instead looking for a specific string, then the checked answer on this is wrong. Instead you should use:

string[] lines = System.IO.File.ReadAllLines("File.txt");

int skip = 3;

string word = "foo";

string pattern = string.Format("\\b{0}\\b", word);

for (int i = 0; i < lines.Count(); i++)
{
    var match = System.Text.RegularExpressions.Regex.IsMatch(lines[i], pattern);

    System.Diagnostics.Debug.Print(string.Format("Line {0}: {1}", Array.IndexOf(lines, lines[i], i) + 1, match));

    if (match) i += skip;


}

If you use the string.contains method and the word you are searching for is "man", while your text somewhere contains "mantle" and "manual", the string.contains method will return as true.

Upvotes: 0

sexta13
sexta13

Reputation: 1568

// read file
List<string> query = (from lines in File.ReadLines(this.Location.FullName, System.Text.Encoding.UTF8)
                    select lines).ToList<string>();

for (int i = 0; i < query.Count; i++)
{
    if (query[i].Contains("TextYouWant"))
    {
        i = i + 3;
    }
}

Upvotes: 0

Dave Bish
Dave Bish

Reputation: 19646

You can do something like this:

var text = File.ReadAllLines("path"); //read all lines into an array
var foundFirstTime = false;
for (int i = 0; i < text.Length; i++)
{
    //Find the word the first time
    if(!foundFirstTime && text[i].Contains("word"))
    {
        //Skip 3 lines - and continue
        i = Math.Min(i+3, text.Length-1);
        foundFirstTime = true;
    }

    if(foundFirstTime && text[i].Contains("word"))
    {
        //Do whatever!
    }
}

Upvotes: 1

Related Questions