check if string exists in a file
Sounds overly complex, no reason to check by line or anything if you want to know if a string is present in a file. You can replace all of your code simply with :
if(File.ReadAllText(path).Contains(domain))
{
MessageBox.Show("There is a match");
}
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!
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.