-2

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;
    }
  }
}
Jimi
  • 29,621
  • 8
  • 43
  • 61
vitem
  • 15
  • 6
  • do not take into account the ``` was my fault when putting the code, that is not there in the original code – vitem Aug 29 '21 at 18:26
  • The procedure is searching for `a`. Change `if(txt_text.Contains("a"))` to `txt_text.Contains(_words)`. – A.Mokhtari Aug 29 '21 at 18:33
  • @PoulBak, As written in the example `words` is an array, but `_words` is an array element. Actually, code's naming need to improve. – A.Mokhtari Aug 29 '21 at 19:16

2 Answers2

1

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";
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • @vitem: Once you're able to, please mark Dmitry's answer as accepted by clicking the checkmark next to it. That will mark this question as resolved, and reward Dmitry for his contribution. Don't explicitly mark your question as "closed" in the title (I've rolled back that change). – Jeremy Caney Aug 29 '21 at 20:24
0

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)

K. L.
  • 231
  • 2
  • 12