70. Find and Replace

The parts of this program that actually find files and make replacements are relatively straightforward. The following code shows how the example solution searches for files:

// Search the directory.
private void findButton_Click(object sender, EventArgs e)
{
Cursor = Cursors.WaitCursor;
filesCheckedListBox.DataSource = null;
Refresh();

// Get the patterns.
string patternsString = patternsComboBox.Text;
if (patternsString.Contains(':'))
patternsString =
patternsString.Substring(
patternsString.IndexOf(':') + 1).Trim();

string[] patterns = patternsString.Trim().Split(
new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

// Find files matching the patterns and containing the target text.
DirectoryInfo dirinfo = new DirectoryInfo(directoryTextBox.Text);
FileInfo[] fileinfos = dirinfo.FindFiles(patterns,
targetTextBox.Text, SearchOption.AllDirectories);

// List the files.
filesCheckedListBox.DataSource = fileinfos;

Cursor = Cursors.Default;
}

This code separates the user's selected file patterns, as in the preceding solution. Next, it creates a DirectoryInfo object and calls its FindFiles extension method to find matching files. It then simply displays the results in the CheckedListBox named filesCheckedListBox.

The following code shows how the program makes replacements in the files that are checked in the CheckedListBox:

// Replace the target text with the replacement text in 
// the selected files.
private void replaceButton_Click(object sender, EventArgs e)
{
string changeFrom = targetTextBox.Text;
string changeTo = replaceWithTextBox.Text;
int numReplacements = 0;
foreach (FileInfo fileinfo in filesCheckedListBox.CheckedItems)
{
MakeReplacement(fileinfo, changeFrom, changeTo);
numReplacements++;
}
MessageBox.Show("Made replacements in " +
numReplacements.ToString() + " files.");

// Clear the file list.
filesCheckedListBox.DataSource = null;
}

This code gets the target and replacement strings. It then loops through the checked files and calls the MakeReplacement method, which is described shortly, for each. The code finishes by displaying the number of files that were modified.

The following code shows the MakeReplacement method:

// Replace changeFrom to changedTo in the file.
private void MakeReplacement(FileInfo fileinfo, string changeFrom,
string changeTo)
{
string file = File.ReadAllText(fileinfo.FullName);
file = file.Replace(changeFrom, changeTo);
File.WriteAllText(fileinfo.FullName, file);
}

This method uses File.ReadAllText to read the file's contents. It uses the string class's Replace method to make the replacement and then uses File.WriteAllText to save the result back into the file.

Download the FindAndReplace example solution to see additional details.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset