I have a .txt file that contains:
123456
45789
check
check
I want to replace check
to now
, I wrote the following code but the result was not as I expected:
123456
45789
now
nowheck
I wonder why the last line became nowheck
.
My code:
StreamReader reader = new StreamReader(File.OpenRead(@"C:\Users\jzhu\Desktop\test1.txt"));
string fileContent = reader.ReadToEnd();
reader.Close();
fileContent = fileContent.Replace("check", "now");
StreamWriter writer = new StreamWriter(File.OpenWrite(@"C:\Users\jzhu\Desktop\test1.txt"));
writer.Write(fileContent);
writer.Close();
The problem is that File.OpenWrite
is reopening the same file for writing without truncating it first.
You could use File.Create
instead, or better yet use the methods which make reading and writing text simple:
string path = @"C:\Users\jzhu\Desktop\test1.txt";
string fileContent = File.ReadAllText(path);
fileContent = fileContent.Replace("check", "now");
File.WriteAllText(path, fileContent);
See more on this question at Stackoverflow