Search and Replace strings in files
June 25th, 2009 — Brian FooteSearchAndReplaceThe other day I ran into a problem where I needed to change the name of an URL for a website which was hard-coded in a bunch of legacy asp code. Now usually I would use a tool such as EditPlus, use the Find in Files function, open the matching files and use search and replace to update them. But in this case there were hundreds of files affected and I didn’t really want to open hundreds of files in a single EditPlus session so instead I searched around the net looking for an easy Search and Replace program. I didn’t really find anything I liked so I thought I’d create a simple utility.
Search and Replace is a windows program which searches folders and subfolders for a specified string in a list of files and replaces that string if desired. Here is the interface I came up with:

Here I’ve searched for “Badda Bing!” in all text files in my test folder and I included subfolders. When a match is found the name of the file is displayed and when the search completes the Results label is updated to display the files found. Note that multiple occurrences are only displayed once.
Here is the main loop which does all the work:
foreach (string fileName in filenames)
{
// Open a file for reading
StreamReader streamReader;
streamReader = File.OpenText(fileName);
// Now, read the entire file into a string
string contents = streamReader.ReadToEnd();
streamReader.Close();
if (Regex.IsMatch(contents, txtFind.Text, RegexOptions.IgnoreCase))
{
ListOfFiles.Items.Add(fileName);
if (Replace)
{
// Write the modification into the same file
StreamWriter streamWriter = File.CreateText(fileName);
streamWriter.Write(Regex.Replace(contents, txtFind.Text, txtReplace.Text, RegexOptions.IgnoreCase));
streamWriter.Close();
}
}
}
After finding all the files and placing them in the array filenames, I loop through each file, load all the contents, check to see if there is a match and then make the replacement. I open the files as text so don’t use this with binary files or they could get corrupted. Also along these lines, using *.* for File Type is probably not a good idea!
Here’s the source: SearchAndReplace.zip

