Win Coder Win Coder -4 years ago 108
C# Question

How to Find And Replace Text In A File With C#

My code so far

StreamReader reading = File.OpenText("test.txt");
string str;
while ((str = reading.ReadLine())!=null)
if (str.Contains("some text"))
StreamWriter write = new StreamWriter("test.txt");

I know how to find the text, but I have no idea on how to replace the text in the file with my own.

Answer Source

Read all file content. Make a replacement with String.Replace. Write content back to file.

string text = File.ReadAllText("test.txt");
text = text.Replace("some text", "new value");
File.WriteAllText("test.txt", text);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download