Find and replace a specific text in C#

  • Thread starter Thread starter amit
  • Start date Start date
A

amit

hi,

I want to find out that if there is a mechanism to find a text inside a C# file and replace it with another string. I am currently doing it with regex.match and thru streamreader class, but I believe it would be very time consuming, please reply ASAP to tell if there is a better solution or how can i optimize this code also.

bye
amit
 
If it is an "exact" match, I suggest you use String.Replace instead of
regular expressions:

string fileName = ...; // the file name
StreamReader sr = new StreamReader(fileName);

string content = sr.ReadToEnd();
sr.Close();

StreamWriter sw = new StreamWriter(fileName);

sw.WriteLine(content.Replace("debt", "profit");
sw.Close();

Hope that helps,
-JG
 
Back
Top