Jun 07
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; /// <summary> /// Replaces text in a file. /// </summary> /// <param name="filePath">Path of the text file.</param> /// <param name="searchText">Text to search for.</param> /// <param name="replaceText">Text to replace the search text.</param> 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(); }
Amazing..i went through loads of method for replace but this is the most sleek and crisp way..thanks for posting π
I ran your code on a 170 MB file and it failed miserably. Could you suggest better ways of modifying this program so that it works on huge datasets as well ?
Rakesh: Yes, of course this code fails miserably on a 170MB file. That’s why the article states, “Because this sample loads the entire file contents in memory, it is not appropriate for very large files.”
To search/replace in large files, you need to load and save the files in manageable-size blocks. Here is code on how to read/write files using TextReader/TextWriter:
http://www.csharphelp.com/archives/archive24.html
Timm your link doesnt say jack about replacing though and thats what this is for.
That’s correct, the other article just shows how to read/write a large file. You can use the Regex method shown in my code above to actually do the replace.
But there’s a hitch… what about a search term that spans two consecutive blocks of data that are read separately? Maybe that can be a topic for a subsequent article.
Good article. I noticed the comments about “very large” files. What constitutes “very large”?
I am working on an application that will be fine today because the files it reads are fairly small. I want to check the file size and determine how I should perform the replace based on the size. What would you suggest as an appropriate size?
Thanks in advance for your response.
Thanks! It really helped me!
I must comment on Rakesh’s bad manners!
The article states the methods limitations! What part of “is not appropriate for very large files.” can he not understand!
Then he compounds his bad manners by moaning about a link the author gives him.
If I was the author, I would not have replied to such an ill mannered person.
Timm, I thank you for your time and effort.
You will need…
using System.Text.RegularExpressions; // for Regex
“But there’s a hitchβ¦ what about a search term that spans two consecutive blocks of data that are read separately? Maybe that can be a topic for a subsequent article.”
This is exactly the problem I am faced with. Is there any solution you can suggest?
I have also been dealing with the problem of too large files to completly read into the memory. Now I have created a method that will replace occurences in a text file without dealing with memory issues. How can I post the code to this website so that you can benefit from it? I can’t see a place to aquire membership to C# 411. This is also my first comment on this site…
Hi Kevin, you can post the code in a comment here, but the WordPress comment formatting is poor, everything gets left-adjusted.
A better solution, if you are interested, is you can send me the code, and I can publish an article with it, of course giving you full credit. It would be a great service to our readers.
You can contact us at “info at tiwebb dot com”
Thank you!
Hi timm, I have just send an email to the emailaddress you provided.
Hope to be hearing from you.
Here’s some good code on this subject:
http://towardsnext.wordpress.com/2009/02/02/replace-data-in-file-c/
Thanks, very easy way to solve the hard job I was planning…
Nice easy search and replace!
Very helpful. Thank you very much!
The snippett did not work for me. I received invalid token errors when I attempted to add a path to the paramater definition.
I’m a noob so I know I’m missing something.
I’m unable to make this code snippett work. I tries the ,param and that failed. I changed that to adding values to string variables, that did not work ( see attached code) Any help would begreatly appreciated.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace FindReplaceLogLevel
{
public class Program
{
public void Main(string[] args)
{
string filePath = (@”C:goatgoattest”);
string searchText = (“goat”);
string replaceText = (“mutton”);
}
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();
}
}
}
Nice article.
I thought I share this – it will probably be good complementary information for the article.
When I need to do a quick and dirty search and replace, I use biterscripting. Here are some sample scripts.
– Script to replace “ABC” with “XYZ” in file X.txt.
var str content
cat “X.txt” > $content
sal “^ABC^” “XYZ” $content > null
echo $content > “X.txt”
– Script to perform many replace operations on the same file X.txt. (I create a file C:/ReplaceList.txt in which the first field is ABC, the second field is XYZ. The fields are separated by tabs. One replace entry per line.)
var str content, searchstr, replacestr, entry, entrylist
set $wsep=”t”
cat “X.txt” > $content
cat “C:/ReplaceList.txt” > $entrylist
lex “1” $entrylist > $entry
while ($entry “”)
do
wex -p “1” $entry > searchstr
wex -p “2” $entry > replacestr
sal (“^”+$searchstr+”^”) $replacestr $content > null
lex “1” $entrylist > $entry
done
echo $content > “X.txt”
– Script to perform many replace operations on every .txt file in folder C:/folder. (The same C:/ReplaceList.txt file is used to specify what to replace with what.)
var str content, searchstr, replacestr, entry, entrylist, filelist, file
set $wsep=”t”
lf -n “*.txt” “C:/folder” > $filelist
while ($filelist “”)
do
lex “1” $filelist > $file
cat $file > $content
cat “C:/ReplaceList.txt” > $entrylist
lex “1” $entrylist > $entry
while ($entry “”)
do
wex -p “1” $entry > searchstr
wex -p “2” $entry > replacestr
sal (“^”+$searchstr+”^”) $replacestr $content > null
lex “1” $entrylist > $entry
done
echo $content > { echo $file }
done
The command we are using is sal (string alterer). Its help page is at http://www.biterscripting.com/helppages/sal.html. One can also use regular expressions with this command.
what is the regex for string constant in C#?
for example:
printf(“Hello World”);
output:
also what is the regex for deleting comment?
my comment started with ‘+’ and ends in ‘+’?
i tried this regex
string regex = (\s*)(//.*n|/\*(.|n)*?\*/)(\s*n);
Lines[i] = Regex.Replace(Lines[i], regex, “” , RegexOptions.IgnorePatternWhitespace);
it only reads “‘/*’ comment ‘*/'”.
i tried to replace the regex with (\s*)(/+.n|/\*(.|n)*?\+)(\s*n). unfortunately it shows, it doesnt hide.
how would i do that is C#?
Very helpful Post.
Keep up the good work. π
how can i search for text in textbox und replace it…..pls help
provided that the serch text is given in one txt box and replace text is given in another text box,and i already have txt in richtext box/……
Thank you very much, that’s just what I needed =]
Nice! this is where i start learning ABC.
Great man, that was really like a super gift for me
Thanks and Good Luck π
u saved my 20 minutes .thanks
thank you very much!
THis is My First Programe… not Hello world
how do you work around this?
System.UnauthorizedAccessException: Access to the path ‘C:\Program Files\Microsoft\XXX_Test\yyyyyy\xxxxx\SqlScripts\AddAlertTypeIdColumn.sql’ is denied.
http://unlimit.in/Search-and-replace-with-regular-expressions-in-net.html
Nice article. A well stated problem, and a simple and correct solution. I’d like to recommend it with google+, but there’s no button π
The variable names are in different places but it doesn’t explain how to use it. Where am I supposed to write “C:\test.txt”, “country”, “homeland” for example.
What are the Param tags for? HTML? This is confusing and doesn’t make sense to people learning C#.
The tags are for documentation to explain what each parameter does.
To use this function:
ReplaceInFile( @”C:\test.txt”, “country”, “homeland” );
The @ sign indicates that the backslash in your string is a backslash and not an escape character.