我要编写的代码是替换文本文件中的单词字符串。尽管我可以读取文件的内容以进行控制台,但是我无法替换字符串并向文件中写入新的字符串。
这是我的代码:
EditTexts
问题在于.Replace删除了文本文件中的所有内容,仅插入目录的路径。
答案 0 :(得分:6)
好吧,我所看到的问题是a)您正在读取文件,但未将文本分配给变量b)您实际上没有执行替换操作,并且c)实际上是在将文件名写入输出。
您不需要使用流,因此您的代码可以简化为:
var contents = File.ReadAllText(e.FullPath);
contents = contents.Replace(text, newText);
File.WriteAllText(e.FullPath, contents);
看来您正在使用FileSystemWatcher来拾取文件,因此请注意,这将(至少)触发Changed
事件。
答案 1 :(得分:0)
您正在将FullPath写入文件,请尝试以下操作:
var text = null;
using (StreamReader sr = new StreamReader(e.FullPath))
{
text = sr.ReadToEnd();
Console.WriteLine(text);
}
using (StreamWriter sw = new StreamWriter(e.FullPath))
{
var replaced = text.Replace("The words I want to replace", "text I want it to be replaced with");
sw.Write(replaced);
}