[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 for target strings in C#

[Search files for target strings in C#]

This example lets you select one or more files and then search them for target strings.

When you select the File menu's Open command, the following code lets you select files.

private void mnuFileOpen_Click(object sender, EventArgs e) { if (ofdFiles.ShowDialog() == DialogResult.OK) { lvwFiles.Items.Clear(); lvwFiles.Columns.Clear(); lvwFiles.Columns.Add("Full Name"); lvwFiles.Columns.Add("Name"); lvwFiles.Columns[0].Width = 20; lvwFiles.Columns[1].Width = 200; foreach (string filename in ofdFiles.FileNames) { FileInfo file_info = new FileInfo(filename); ListViewItem item = lvwFiles.Items.Add(file_info.FullName); item.SubItems.Add(file_info.Name); } } }

This code clears the ListView control lvwFiles and adds two columns titled Full Name and Name.

Next the code loops through the files that you selected. For each file, it adds a FileInfo item to the ListView. A FileInfo object's ToString method returns the full name of the file, so the ListView uses that to show the file in its list. That value is too long to see easily, so the program also adds the file's short name as a sub-item so you can see it more easily.

When you enter a string in the text box and click Search, the following code executes.

private void btnSearch_Click(object sender, EventArgs e) { string word = txtWord.Text.Trim(); lvwFiles.Columns.Add(word); foreach (ListViewItem item in lvwFiles.Items) { try { string filename = item.SubItems[0].Text; string text = File.ReadAllText(filename); int pos = 0; int count = 0; for (; ; ) { pos = text.IndexOf(word, pos, StringComparison.OrdinalIgnoreCase); if (pos < 0) break; count++; pos++; } item.SubItems.Add(count.ToString()); } catch (Exception ex) { item.SubItems.Add(ex.Message); } } }

This code gets the word that you entered and adds a new sub-item to the ListView. It gives that sub-item's column the target word as its title.

Next, the program loops through the FileInfo objects in the ListView. The code reads each file into a string and uses a loop to count the instances of your target string in the file's contents. After it finishes searching for the word, the program adds the count to the target's ListView column.

Download the example to experiment with it and to see additional details.

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