【发布时间】:2015-07-28 04:52:50
【问题描述】:
我正在编写这个程序来替换文本文件中字符串第 n 位的字符。我的文本文件包含以下内容 -
the quick brown fox jumped over the lazy dog
the quick brown fox jumped over the lazy dog
the quick brown fox jumped over the lazy dog
the quick brown fox jumped over the lazy dog
这是代码的输出 -
thehuick brown fox jumped over the lazy dog
上面的结果不是我想要的。只更新了一行,其余的在文件中都找不到了。
这是我用 C# 编写的完整代码
var txtFiles = Directory.GetFiles(@"E:\PROJ\replaceY\replaceY\", "*.txt");
foreach (string currentFile in txtFiles)
{
string[] lines = File.ReadAllLines(currentFile);
foreach (string line in lines)
{
var theString = line;
var aStringBuilder = new StringBuilder(theString);
aStringBuilder.Remove(3, 2);
aStringBuilder.Insert(3, "h");
theString = aStringBuilder.ToString();
using (StreamWriter outfile = new StreamWriter(currentFile))
{
outfile.Write(theString.ToString());
}
Console.WriteLine(theString);
Console.ReadKey();
}
}
我哪里出错了?请帮忙!
【问题讨论】:
-
这实际上可能是最后一行,因为您在每次循环迭代中都覆盖了文件。试试
new StreamWriter(currentFile, true) -
它只是在最后一行追加新字符串
-
是的,你写的是我忘记了一个额外的步骤,因为你从你正在写入的同一个文件中读取,检查我的答案