Search files for target text in C#

[search files]

The .NET tools available in the System.IO namespace and normal string methods make it easy to search files for target text. When you click the Search button, the following code displays the lines in a file that contain a particular string.

// Search for lines containing the target text.
private void btnSearch_Click(object sender, EventArgs e)
{
    lstResults.Items.Clear();
    lblResults.Text = "";
    Refresh();

    string target = txtTarget.Text;
    string[] lines = File.ReadAllLines(txtFile.Text);
    foreach (string line in lines)
        if (line.Contains(target))
            lstResults.Items.Add(line);

    lblResults.Text = lstResults.Items.Count.ToString() + " matches";
}

This code gets the target text. It then uses File.ReadAllLines to read the file into an array holding the file’s lines.

The code then loops through the lines and uses each line’s Contains method to see if the line contains the target text. If the line does contain the text, then the program adds it to the ListBox named lstResults.

The code finishes by displaying the number of lines saved into the ListBox.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in files and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.