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

Bry*_*est 6 c# string streamreader

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

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

检查此代码:

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

Ron*_*dau 21

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

if(File.ReadAllText(path).Contains(domain))
{
    MessageBox.Show("There is a match");
}
Run Code Online (Sandbox Code Playgroud)


gpm*_*thy 5

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

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

祝好运!