Saturday, January 29, 2011

Search/Replace in Files in C#

Sometimes you need a quick & easy way to search and replace text in a file. The following code shows how it can be done using the static methods on the Regex regular expression class. Because this sample loads the entire file contents in memory, is not appropriate for very large files.

using System;
using System.IO;
using System.Text.RegularExpressions;

///
/// Replaces text in a file.
///

/// Path of the text file.
/// Text to search for.
/// Text to replace the search text.
static public void ReplaceInFile( string filePath, string searchText, string replaceText )
{
StreamReader reader = new StreamReader( filePath );
string content = reader.ReadToEnd();
reader.Close();

content = Regex.Replace( content, searchText, replaceText );

StreamWriter writer = new StreamWriter( filePath );
writer.Write( content );
writer.Close();
}

No comments:

Post a Comment

Ajax CalendarExtender displaying at wrong position in Chrome

< script type ="text/javascript" language ="javascript">     function onCalendarShown(sender, args)...