vitem
vitem

Reputation: 15

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

Upvotes: -2

Views: 1017

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186823

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";

Upvotes: 1

K. L.
K. L.

Reputation: 261

I'd save the text in a variable and then loop over your words to check if it exists in the file. Something like this:

string[] words = { "var", "bob", "for", "example"};
var text = file.ReadToEnd();

List<string> foundWords = new List<string>();

foreach (var word in words)
{
    if (text.Contains(word))
        foundWords.Add(word);
}

Then, the list foundWords contains all matching words.

(PS: Don't forget to put your StreamReader in a using statement so it gets disposed correctly)

Upvotes: 0

Related Questions