user1753911 user1753911 - 1 month ago 19
C# Question

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

Answer
Dictionary<string, string> found = new Dictionary<string, string>();
string line;
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");
            }
            if (line.Contains("Warning: 1"))
            {
                found.Add(line,filename);
                MessageBox.Show("Warning Found");
            }

        }   
    }  
}
Comments