Click here to Skip to main content
Click here to Skip to main content

Tagged as

Mass Find & Replace

, 9 Feb 2009
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

bcryner
Other
United States United States
No Biography provided

Comments and Discussions

 
QuestionThanks PinmemberManjuke Fernando6-Oct-13 14:47 
Questionhow to use directory Pinmemberabdulyar16-Aug-11 10:53 
QuestionHow to find text within image file ? PinmemberMember 35224788-Apr-09 1:14 
GeneralYuck PinmemberPIEBALDconsult9-Feb-09 17:29 
GeneralRe: Yuck Pinmemberbcryner10-Feb-09 3:10 
GeneralRe: Yuck PinmemberPIEBALDconsult10-Feb-09 3:53 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140827.1 | Last Updated 9 Feb 2009
Article Copyright 2009 by bcryner
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid