C# 无法替换文本文件中的字符串
我试图编写的代码是替换文本文件中的字符串。虽然我能够将文件内容读取到控制台,但我无法替换字符串并将新字符串写入文件 这是我的密码:C# 无法替换文本文件中的字符串,c#,.net,C#,.net,我试图编写的代码是替换文本文件中的字符串。虽然我能够将文件内容读取到控制台,但我无法替换字符串并将新字符串写入文件 这是我的密码: private static void filesys_created (object sender, FileSystemEventArgs e) { using (StreamReader sr = new StreamReader(e.FullPath)) { Console.WriteLine(sr.ReadToEnd());
private static void filesys_created (object sender, FileSystemEventArgs e)
{
using (StreamReader sr = new StreamReader(e.FullPath))
{
Console.WriteLine(sr.ReadToEnd());
File.ReadAllText(e.FullPath);
sr.Close();
}
using (StreamWriter sw = new StreamWriter(e.FullPath))
{
string text = e.FullPath.Replace("The words I want to replace");
string newtext = "text I want it to be replaced with";
sw.Write(e.FullPath, text);
sw.Write(newtext);
sw.Close();
}
}
问题是.Replace删除了文本文件中的所有内容,只插入了目录的路径。我看到的问题是a)您正在读取文件,但没有将文本分配给变量b)您实际上没有进行替换,c)您确实在将文件名写入输出 您不需要使用流,因此您的代码可以简化为:
var contents = File.ReadAllText(e.FullPath);
contents = contents.Replace(text, newText);
File.WriteAllText(e.FullPath, contents);
看起来您正在使用FileSystemWatcher来提取文件,因此请注意,这将触发(至少)一个
更改的事件。如果要将完整路径写入文件,请尝试以下操作:
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);
}
谢谢你,斯图尔特!这解决了问题:)