check if string exists in a file

后端 未结 7 1685
猫巷女王i
猫巷女王i 2021-02-09 19:36

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

7条回答
  •  爱一瞬间的悲伤
    2021-02-09 20:04

    Simplest way:

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

    and now to analyze your code:

    1st, you are creating StreamReader instance, but you don't use it later in your code.

    2nd, what if domain name has multiple occurrence in the file? In your code you will get multiple 'there is a match' in your code.

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

提交回复
热议问题