Search for text in process

108 views Asked by At

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

There are 2 answers

4
Liath On

There are many approaches to this problem, the simplest is probably the following:

using (OpenFileDialog open = new OpenFileDialog())
{
    if (open.ShowDialog() == DialogResult.OK)
    {
        if (File.ReadAllText(open.FileName).Contains("Example"))
        {
            MessageBox.Show("Found");
        }
    }
}

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:

using (OpenFileDialog open = new OpenFileDialog())
        {
            if (open.ShowDialog() == DialogResult.OK)
            {
                using (StreamReader sr = new StreamReader(open.FileName))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        if (line.Contains("Example"))
                        {
                            MessageBox.Show("Found");
                            break;
                        }
                    }
                }
            }
        }
4
Mike Perrenoud On

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:

  1. You only read one line at a time.
  2. You may not have to read the entire file. If the text is found on line 2, only 2 lines are ever read from the file.

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.