Click here to Skip to main content
15,300,338 members
Articles / Programming Languages / C#
Posted 9 Feb 2009

Tagged as


11 bookmarked

Mass Find & Replace

Rate me:
Please Sign up or sign in to vote.
2.82/5 (5 votes)
9 Feb 2009CPOL1 min read
Finds and replaces specified text in a directory of files


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
		//Increment the 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

		//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;


  • 2/9/2009 - Initial release 


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

United States United States
No Biography provided

Comments and Discussions

QuestionThanks Pin
Manjuke Fernando6-Oct-13 14:47
professionalManjuke Fernando6-Oct-13 14:47 
Thanks.. This solution did save lot of my time..
Manjuke Fernando

Questionhow to use directory Pin
abdulyar16-Aug-11 10:53
Memberabdulyar16-Aug-11 10:53 
QuestionHow to find text within image file ? Pin
Member 35224788-Apr-09 1:14
MemberMember 35224788-Apr-09 1:14 
GeneralYuck Pin
PIEBALDconsult9-Feb-09 17:29
professionalPIEBALDconsult9-Feb-09 17:29 
GeneralRe: Yuck Pin
bcryner10-Feb-09 3:10
Memberbcryner10-Feb-09 3:10 
GeneralRe: Yuck Pin
PIEBALDconsult10-Feb-09 3:53
professionalPIEBALDconsult10-Feb-09 3:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.