check if string exists in a file

后端 未结 7 1688
猫巷女王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:11

    Actually you don't need to read whole file into memory. There is File.ReadLines method which allows you enumerate file lines one by one, without reading whole file. You can create following method

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

    Usage of this method looks like:

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

    Also two side notes - you don't need StreamReader if you are reading lines with File.ReadAllLines (it creates reader internally). Just check - you even don't use sr variable anywhere. And second note - you don't need to manually close stream, if you wrapped it in using block. In that case stream will be disposed and closed automatically.

提交回复
热议问题