【问题标题】:Unable to replace string from text file [duplicate]无法从文本文件中替换字符串 [重复]
【发布时间】:2019-04-03 09:51:21
【问题描述】:

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

这是我的代码:

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 删除了文本文件中的所有内容,只插入了目录的路径。

【问题讨论】:

    标签: c# .net


    【解决方案1】:

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

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

    var contents = File.ReadAllText(e.FullPath);
    contents = contents.Replace(text, newText);
    File.WriteAllText(e.FullPath, contents);
    

    看起来您正在使用 FileSystemWatcher 来获取文件,因此请注意这将触发(至少)Changed 事件。

    【讨论】:

    • 谢谢斯图尔特!这解决了问题:)
    【解决方案2】:

    您正在将 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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-28
      • 2013-04-05
      • 1970-01-01
      • 2011-06-30
      • 1970-01-01
      • 2017-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多