【问题标题】:check if string exists in a file检查文件中是否存在字符串
【发布时间】:2013-12-01 06:08:27
【问题描述】:

我有以下代码打开一个文本文件并读取文件中的所有行并将其存储到字符串数组中。

然后检查字符串是否存在于数组中。 但是我面临的问题是,每当找到一个字符串时,它总是显示 “有一个匹配” 以及“没有匹配”。 知道如何解决这个问题吗?

检查此代码:

using (StreamReader sr = File.OpenText(path))
{
    string[] lines = File.ReadAllLines(path);
    for (int x = 0; x < lines.Length - 1; x++)
    {
        if (domain == lines[x])
        {
            sr.Close();
            MessageBox.Show("there is a match");
        }
    }
    if (sr != null)
    {
        sr.Close();
        MessageBox.Show("there is no match");
    }
}

【问题讨论】:

    标签: c# string streamreader


    【解决方案1】:

    听起来过于复杂,如果您想知道文件中是否存在字符串,没有理由逐行检查或其他任何内容。您可以简单地将所有代码替换为:

    if(File.ReadAllText(path).Contains(domain))
    {
        MessageBox.Show("There is a match");
    }
    

    【讨论】:

      【解决方案2】:

      我建议如下设置和标记并检查它...

      using (StreamReader sr = File.OpenText(path))
      {
          string[] lines = File.ReadAllLines(path);
          bool isMatch = false;
          for (int x = 0; x < lines.Length - 1; x++)
          {
              if (domain == lines[x])
              {
                  sr.Close();
                  MessageBox.Show("there is a match");
                  isMatch = true;
              }
          }
          if (!isMatch)
          {
              sr.Close();
              MessageBox.Show("there is no match");
          }
      }
      

      祝你好运!

      【讨论】:

        【解决方案3】:

        实际上,您不需要将整个文件读入内存。有File.ReadLines 方法可以让您一一枚举文件行,而无需读取整个文件。您可以创建以下方法

        private bool DomainExists(string domain)
        {
            foreach(string line in File.ReadLines(path))
                if (domain == line)
                    return true; // and stop reading lines
        
            return false;
        }
        

        这个方法的用法如下:

        if (DomainExists(domain))
            MessageBox.Show("there is a match");
        else
            MessageBox.Show("there is no match");
        

        还有两个旁注 - 如果您正在阅读带有 File.ReadAllLines 的行(它在内部创建阅读器),则不需要 StreamReader。只需检查 - 您甚至不会在任何地方使用 sr 变量。第二个注意事项 - 如果您将其包装在 using 块中,则无需手动关闭流。在这种情况下,流将被自动释放和关闭。

        【讨论】:

          【解决方案4】:

          最简单的方法:

          string content = File.ReadAllText(path);
          if (content.IndexOf(domain) > -1)
          {
             // domain exists
          }
          else
          {
             // domain does not exist
          }
          

          现在分析您的代码:

          首先,您正在创建 StreamReader 实例,但您稍后不会在代码中使用它。

          2、如果域名在文件中出现多次怎么办?在您的代码中,您将在代码中获得多个“匹配项”。

          using (StreamReader sr = File.OpenText(path)) // you can remove this line
          {
              string[] lines = File.ReadAllLines(path); // as you are not using it here
              for (int x = 0; x < lines.Length - 1; x++)
              {
                  if (domain == lines[x])
                  {
                      sr.Close();
                      MessageBox.Show("there is a match");
                      hasMatch = true;
                      break; // exit loop if found
                  }
              }
          
              if (!hasMatch)
              {
                  // there is no match
              }
          
              if (sr != null) // you dont need this if you remove it from the beginning of the code
              {
                  sr.Close();
                  MessageBox.Show("there is no match");
              }
          }
          

          【讨论】:

            【解决方案5】:

            你可以试试这个:


            首先您需要创建一个接收字符串类型数组的方法,然后我们将该数组转换为字符串,然后我们从 txt 中读取所有文本并可以使用 (Contains)了解我们发送的文本是否存在于我们的 txt 中,并验证其是真是假,希望对您有所帮助。

                    public static void TextValidation(string[] val){
                        //Path of your file
                        string path = "/Users/Desktop/YourFile.txt";
                        //Array to string
                        string b = string.Join(",",val);
                        //Validate if exists
                        if(File.ReadAllText(path).Contains(b)){
                            Console.WriteLine("found");
                            // Do something if the data is found
                        }else{
                            Console.WriteLine("Not found");
                        }
                    }
            

            【讨论】:

            • 欢迎来到 StackOverflow!介意您解释一下这是如何解决问题的吗?谢谢!
            【解决方案6】:

            你可以试试这个代码:

             using (StreamReader sr = File.OpenText(path))
                                    {
                                        string[] lines = File.ReadAllLines(path);
                                        for (int x = 0; x < lines.Length - 1; x++)
                                        {
                                            if (lines[x].Contains(domain, StringComparison.InvariantCultureIgnoreCase)
                                            {
                                                sr.Close();
                                                MessageBox.Show("there is a match");
                                            }
                                        }
                                        if (sr != null)
                                        {
                                            sr.Close();
                                            MessageBox.Show("there is no match");
                                        }
                                    }
            

            【讨论】:

            • 即使找到匹配项,它仍然会显示“没有匹配项”对话框。如果您想强调string.Contains() 的使用,我会澄清答案。
            【解决方案7】:

            尝试尝试捕捉:

            string x;
            
            string log = @"C:\Users\Log.txt";
            
            string ruta = @"C:\Users\x.txt";
            
            if (File.Exists(ruta))
            {                    
                try
                {
                    x = File.ReadAllText(ruta);  
                }
                catch (Exception ex)
                {
                    File.AppendAllText(ruta, "Something");
                    File.AppendAllText(log, Environment.NewLine + DateTime.Now.ToString() + ": The file not contain a string. " + ex.Message);
                }
            }
            

            【讨论】:

            • 请解释你的答案。
            猜你喜欢
            • 1970-01-01
            • 2014-12-11
            • 2021-10-07
            • 2019-02-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-01-08
            • 2020-04-10
            相关资源
            最近更新 更多