繁体   English   中英

使用c#在多个文件中搜索字符串

[英]Search string in multiple files using c#

我想在目录中的多个文件中搜索单词或字符串。 例如 "Error" , "Warning" 如果任何文件包含三个单词中的任何一个,那么它应该在同一目录中打印 messages.all 文件。

使用此代码,我可以在单个文件中搜索一个单词,但我想搜索目录中可用的所有 d 文件。

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

您可以使用正则表达式:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM