[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Search files target text in C#

[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.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.