IO 输出与预期不同

IO Output different from expected

我有一个 .txt 文件,其中包含:

123456
45789
check
check

我想把check替换成now,我写了下面的代码但是结果不是我想的那样:

123456
45789
now
nowheck

我想知道为什么最后一行变成了nowheck

我的代码:

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();

问题是 File.OpenWrite 正在重新打开同一个文件进行写入 而没有先截断它

您可以改用 File.Create,或者更好的是使用使阅读和书写文本变得简单的方法:

string path = @"C:\Users\jzhu\Desktop\test1.txt";
string fileContent = File.ReadAllText(path);
fileContent = fileContent.Replace("check", "now");
File.WriteAllText(path, fileContent);

尝试将输出写入第二个文件。它应该是正确的。问题是原来的内容还在。第二次打开文件时需要截断文件。

File.OpenWrite 正在重新打开同一个文件。 为避免该问题,请尝试 File.Create