Introduction
There have been many times where I've created a batch of files with a specific piece of information, such as a date or id number. Prior to the creation of the mass find & replace tool, I had to manually change each file. The tool was created to take the standard windows find & replace idea and apply it to a whole directory of files.
Using the Code
Although I've added some additional features for my specific needs (BackgroundWorker
, Validation
), there are only a few steps needed to make the app work.
Our first step is to get the directory the user inputted and gather the files within it. We will create a loop that will be used to do the find and replace operation in each file of the directory.
private int DoFindReplace(BackgroundWorker worker)
{
int filesAffectedCount = 0;
int counter = 0;
string[] filesInDirectory = Directory.GetFiles(outputDirectory, "*.txt");
int totalFiles = filesInDirectory.GetLength(0);
foreach (string file in filesInDirectory)
{
if (FindAndReplace(file))
{
filesAffectedCount++;
}
counter++;
worker.ReportProgress((int)((counter / totalFiles) * 100.00));
}
return filesAffectedCount;
}
The next step is to create the method that does the actual find and replace operation. The key steps in this method are to read the file, do the find and replace, and write the file.
private bool FindAndReplace(string file)
{
string content = string.Empty;
using (StreamReader sr = new StreamReader(file))
{
content = sr.ReadToEnd();
}
string searchText = GetSearchText(findWhatString);
if (Regex.IsMatch(content, searchText, GetRegExOptions()))
{
string newText = Regex.Replace
(content, searchText, replaceWithText, GetRegExOptions());
using (StreamWriter sw = new StreamWriter(file))
{
sw.Write(newText);
}
return true;
}
return false;
}
The method above makes a call to the method GetRegExOptions
. The only purpose of this method is to determine if we need to match the case.
private RegexOptions GetRegExOptions()
{
RegexOptions options = new RegexOptions();
if (isMatchCase == false)
options |= RegexOptions.IgnoreCase;
return options;
}
History
- 2/9/2009 - Initial release