Search code examples
c#streamreaderfile.readalllines

Search multiple words in a text file


I made a code to search for several words in a text file but only the last word is searched, I would like to solve it code:

string txt_text;
string[] words = {
  "var",
  "bob",
  "for",
  "example"
};
StreamReader file = new StreamReader("test.txt");
foreach(string _words in words) {
  while ((txt_text = file.ReadToEnd()) != null) {
    if (txt_text.Contains(_words)) {
      textBox1.Text = "founded";
      break;
    } else {
      textBox1.Text = "nothing founded";
      break;
    }
  }
}

Solution

  • First of all, you can get rid of StreamReader and loop and query the file with a help of Linq

    using System.Linq;
    using System.IO;
    
    ...
    
    textBox1.Text = File
      .ReadLines("test.txt")
      .Any(line => words.Any(word => line.Contains(word))) 
         ? "found"
         : "nothing found";
    

    If you insist on loop, you should drop else:

     // using - do not forget to Dispose IDisposable
     using StreamReader file = new StreamReader("test.txt");
    
     // shorter version is
     // string txt_text = File.ReadAllText("test.txt");
     string txt_text = file.ReadToEnd();
    
     bool found = false;
    
     foreach (string word in words) 
       if (txt_text.Contains(word)) {
         // If any word has been found, stop further searching
         found = true;
    
         break; 
       } // no else here: keep on looping for other words
    
     textBox1.Text = found
       ? "found"
       : "nothing found";