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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top