I have a browse function, and i want something like this:
if (browsedFile.Text.Contains("Example")) //If the browsed file contains the text
{
MessageBox.Show("Found");
}
else
{
MessageBox.Show("Not Found");
}
I have a browse function, and i want something like this:
if (browsedFile.Text.Contains("Example")) //If the browsed file contains the text
{
MessageBox.Show("Found");
}
else
{
MessageBox.Show("Not Found");
}
Just for posterity, here is a solution that will work for larger files:
using (OpenFileDialog ofd = new OpenFileDialog())
{
if (ofd.ShowDialog() == DialogResult.OK)
{
foreach (var line in File.ReadLines(ofd.FileName))
{
if (!line.Contains(textToFind)) { continue; }
// do something
}
}
}
The File.ReadLines
method uses what's called deferred execution. In other words, it reads one line of the file into memory at a time and releases the previous when a new one is iterated. There are two advantages with this approach:
However, there is a caveat with this solution. If the text you're looking for contains a new line constant (i.e. you're searching for text across lines) this won't work because you don't have enough context.
It's likely that the solution provided by Liath is quite sufficient for your needs.
There are many approaches to this problem, the simplest is probably the following:
However you've mentioned larger files. If you're reading files with a gig or more you may want to look at the following approach instead: