Click here to Skip to main content
6,685,738 members and growing! (16,980 online)
Email Password   helpLost your password?
Languages » C# » Utilities License: The Code Project Open License (CPOL)

Mass Find & Replace

By bcryner

Finds and replaces specified text in a directory of files
C#, Dev
Version:5 (See All)
Posted:9 Feb 2009
Views:5,592
Bookmarked:6 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
4 votes for this article.
Popularity: 1.57 Rating: 2.60 out of 5
1 vote, 25.0%
1

2
2 votes, 50.0%
3

4
1 vote, 25.0%
5
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)

About the Author

bcryner


Member

Occupation: Other
Location: United States United States

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 4 of 4 (Total in Forum: 4) (Refresh)FirstPrevNext
GeneralHow to find text within image file ? PinmemberMember 35224782:14 8 Apr '09  
GeneralYuck PinmemberPIEBALDconsult18:29 9 Feb '09  
GeneralRe: Yuck Pinmemberbcryner4:10 10 Feb '09  
GeneralRe: Yuck PinmemberPIEBALDconsult4:53 10 Feb '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 9 Feb 2009
Editor: Deeksha Shenoy
Copyright 2009 by bcryner
Everything else Copyright © CodeProject, 1999-2009
Web10 | Advertise on the Code Project