Sagar Trivedi
Sagar Trivedi

Reputation: 47

Search string in multiple files using c#

I want to search word or string in multiple file in directory. for example "Error" , "Warning" If any file contain any of three word then it should print messages.all files in same directory.

With this code I can search one word in single file but I want to search all d file which are available in directory.

      List<string> found = new List<string>();
         string line;
         using (StreamReader file = new StreamReader(textBox1.Text))
         {
             while ((line = file.ReadLine()) != null)
             {
                 if (line.Contains("Error: 1"))
                 {
                     found.Add(line);
        MessageBox.Show("Error Found");
                 }
             }
         } 

Upvotes: 2

Views: 3161

Answers (2)

Akshey Bhat
Akshey Bhat

Reputation: 8545

Dictionary<string, string> found = new Dictionary<string, string>();
string line;
bool textFound = false;
foreach (string filename in Directory.GetFiles("path-to-directory"))
{
    using (StreamReader file = new StreamReader(filename))
    {

        while ((line = file.ReadLine()) != null)
        {
            if (line.Contains("Error: 1"))
            {
                found.Add(line,filename);
                MessageBox.Show("Error Found");
                textFound = true;
            }
            if (line.Contains("Warning: 1"))
            {
                found.Add(line,filename);
                MessageBox.Show("Warning Found");
                textFound = true;
            }
        }          
    }  

}
if(!textFound)
           MessageBox.Show("Your message here");

Upvotes: 2

andres descalzo
andres descalzo

Reputation: 14967

You can use regular expresion:

Regex.Match(line, @"\b(Error: 1|Warning: 1|Others)\b");

Upvotes: 0

Related Questions