无法从文本文件中替换字符串

s4m*_*dev 2 .net c#

我正在尝试编写的代码是替换文本文件中的一串字.虽然我能够将文件的内容读取到控制台,但我无法替换字符串并将新字符串写入文件.

这是我的代码:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是.Replace正在删除文本文件中的所有内容,只插入目录的路径.

stu*_*rtd 6

好吧,我看到的问题是a)你正在读取文件而不是将文本分配给变量b)你实际上并没有进行替换而c)你确实正在将文件名写入输出.

您不需要使用流,因此您的代码可以简化为:

var contents = File.ReadAllText(e.FullPath);
contents = contents.Replace(text, newText);
File.WriteAllText(e.FullPath, contents);
Run Code Online (Sandbox Code Playgroud)

看起来你正在使用FileSystemWatcher来获取文件,因此只需注意这将触发(至少)一个Changed事件.

  • 谢谢Stuart!这解决了问题:) (2认同)