繁体   English   中英

C# 搜索目录中包含字符串的所有文件,然后返回该字符串

[英]C# search all files in a directory that contain a string, then return that string

使用文本框中的用户输入,我想搜索目录中的哪个文件包含该文本。 然后我想解析出信息

但我似乎找不到字符串或至少返回信息。 任何帮助将不胜感激。

我当前的代码:

private void btnSearchSerial_Click(object sender, EventArgs e)
{
    dynamic dirScanner = @"\\mypath\";
    string strSerial;
    string strSID;
    string strInputLine;
    string strOutput;

    strSerial = Convert.ToString(txtSerialSearch);
    strSID = Convert.ToString(txtSID);

    if (txtSerialSearch.Text != "" && txtSID.Text != "")
    {
         try
         {                    
              string[] allFiles = Directory.GetFiles(dirScanner);

              foreach (string file in allFiles)
              {
                   if (file.EndsWith(".txt"))                            
                   {  
                        using (StreamReader sr = new StreamReader(file))
                        {
                              while (sr.Peek() >= 0)
                              {
                                   strInputLine = sr.ReadLine();

                                   if (strInputLine.Contains(strSerial))
                                   {
                                        strOutput = Convert.ToString(strInputLine);
                                        lblOutput.Text = Convert.ToString(strOutput);
                                   }
                              }
                        }
                   }
              }
         }
    }
}

你好像很迷茫。 当你需要一个string时,为什么使用dynamic 您的代码有太多不必要的变量和转换。 这是一种更简单的方法。 如果有很多匹配的线,我不知道你想要的标签,这里我只放置第一个:

string dirScanner = @"\\mypath\";

if (string.IsNullOrWhiteSpace(txtSerialSearch.Text) || string.IsNullOrWhiteSpace(txtSID.Text))
    return;

string[] allFiles = Directory.GetFiles(dirScanner, "*.txt");

foreach (string file in allFiles)
{
    string[] lines = File.ReadAllLines(file);
    string firstOccurrence = lines.FirstOrDefault(l => l.Contains(txtSerialSearch.Text));
    if (firstOccurrence != null)
    {
        lblOutput.Text = firstOccurrence;
        break;
    }
}

我使用正则表达式实现了相同的功能。 您需要using System.Text.RegularExpressions;来使用命名空间using System.Text.RegularExpressions;

 string strSerial = @"Microsoft";
            Regex match = new Regex(strSerial);
            string matchinglines = string.Empty;
            List<string> filenames = new List<string>(Directory.GetFiles(textBox1.Text));
            foreach(string filename in filenames)
            {
                //StreamReader strFile = new StreamReader(filename);
                string fileContent = File.ReadAllText(filename);
                if(match.IsMatch(fileContent))
                {
                    label1.Text = Regex.Match(fileContent, strSerial).ToString();
                    break;
                }
            }

使用 System.LINQ:

private IEnumerable<string> GetFilesWithText(string your_text, string dir)
{
    var list_of_files_that_match = Directory.EnumerateFiles(dir).Where(delegate (string t)
    {
        if (Path.GetExtension(t).Contains("txt"))
            return System.IO.File.ReadAllText(t).Contains(your_text);
        return false;
    });

    return list_of_files_that_match;
    // if this is empty then there were not matches.
}

这对我有用。 快速简单。

暂无
暂无

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

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