Title: Search files target text in C#
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 the example to experiment with it and to see additional details.
|