检查文件中是否存在字符串

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

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

检查此代码:

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

我会建议设置和标记并检查如下…

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

祝好运!

听起来过于复杂,如果你想知道文件中是否存在字符串,没有理由按行检查。 您只需使用以下命令替换所有代码:

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

实际上你不需要将整个文件读入内存。 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块包装它,则不需要手动关闭流。 在这种情况下,流将自动处理和关闭。

最简单的方法:

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

现在来分析你的代码:

1,您正在创建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"); } } 

你可以试试这段代码:

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