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 how to replace the text in the file with my own
Best Answer
Read the contents of the file Make a replacement with String.Replace
. Write the content back to a file
string text = File.ReadAllText("test.txt");
text = text.Replace("some text", "new value");
File.WriteAllText("test.txt", text);