Search code examples
c#stringstreamreader

check if string exists in a file


I have the following piece of code which opens a text file and reads all the lines in the file and storing it into a string array.

Which then checks if the string is present in the array. However the issue I'm facing is that whenever a string is found, it always shows "there is a match" as well as "there is no match". Any idea how to fix this?

check this code:

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

Solution

  • I would recommend seting and flag and checking it as follows...

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

    Good Luck!