Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Mass Find & Replace

0.00/5 (No votes)
9 Feb 2009 1  
Finds and replaces specified text in a directory of files
MassFindAndReplace

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.

/// <summary>
/// Executes the main find and replace operation.
/// </summary>
/// <param name="worker">The BackgroundWorker object.</param>
/// <returns>The number of files affected by the replace operation.</returns>          
private int DoFindReplace(BackgroundWorker worker)
{
	//Initialize the affected count variable
	int filesAffectedCount = 0;

	//Initialize the counter
	int counter = 0;

	//Get all txt files in the directory
	string[] filesInDirectory = Directory.GetFiles(outputDirectory, "*.txt");

	//Initialize total file count
	int totalFiles = filesInDirectory.GetLength(0);

	//Analyze each file in the directory
	foreach (string file in filesInDirectory)
	{
		//Perform find and replace operation
		if (FindAndReplace(file))
		{
			//The file was changed so increment variable
			filesAffectedCount++;
		}
 
		//Increment the counter
		counter++;

		//Report progress
		worker.ReportProgress((int)((counter / totalFiles) * 100.00));
	}
 
	//Return the total number of files changed
	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.

/// <summary>
/// Performs the find and replace operation on a file.
/// </summary>
/// <param name="file">The path of the file to operate on.</param>
/// <returns>A value indicating if the file has changed.</returns>
private bool FindAndReplace(string file)
{
	//holds the content of the file
	string content = string.Empty;

	//Create a new object to read a file	
	using (StreamReader sr = new StreamReader(file))
	{
		//Read the file into the string variable.
		content = sr.ReadToEnd();
	}

	//Get search text
	string searchText = GetSearchText(findWhatString);

	//Look for a match
	if (Regex.IsMatch(content, searchText, GetRegExOptions()))
	{
		//Replace the text
		string newText = Regex.Replace
			(content, searchText, replaceWithText, GetRegExOptions());

		//Create a new object to write a file
		using (StreamWriter sw = new StreamWriter(file))
		{
			//Write the updated file
			sw.Write(newText);
		}

		//A match was found and replaced
		return true;
	}

	//No match found and replaced
	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. 

/// <summary>
/// Adds options to the expression.
/// </summary>
/// <returns>A Regex options object.</returns>
private RegexOptions GetRegExOptions()
{
	//Create a new option
	RegexOptions options = new RegexOptions();

	//Is the match case check box checked
	if (isMatchCase == false)
		options |= RegexOptions.IgnoreCase;

	//Return the options
	return options;
}

History

  • 2/9/2009 - Initial release 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here