搜索和替换文件.net 2.0中的文本。我错过了什么?

时间:2011-11-20 10:05:13

标签: c#

如果你愿意,我有一个带有一些占位符的xml文件。我需要阅读它并搜索占位符。每个占位符都是唯一的。 我想过使用这个方法而不是xpath,因为我从来没有使用它,而且xml文件非常深且复杂。读取字符串然后替换应该做的伎俩。 我错过了一些明显的东西吗?

为什么下面没有搜索和替换?

  using (StreamReader reader = new StreamReader(path))
        {
            string content = reader.ReadToEnd();
            reader.Close();

            content.Replace("FirstReplace", "test1");
            content.Replace("SecondReplace", "test2");
            content.Replace("ThirdReplace", "test3");
            content.Replace("FourthReplace", "test4");
            content.Replace("FifthReplace", "test5");

            using (StreamWriter writer = new StreamWriter(filePath))
            {
                writer.WriteLine(content);
                writer.Close();
            }
        }

任何建议

1 个答案:

答案 0 :(得分:8)

这是因为字符串在.NET中是不可变的,Replace方法返回一个新的字符串实例作为结果。它不会修改原始字符串。所以:

content = content
    .Replace("FirstReplace", "test1")
    .Replace("SecondReplace", "test2")
    .Replace("ThirdReplace", "test3")
    .Replace("FourthReplace", "test4")
    .Replace("FifthReplace", "test5");

当然如果你在紧密循环中有很多替换,那么许多字符串分配可能会开始损害性能,而StringBuilder就是方便的地方:

var sb = new StringBuilder(content);
    .Replace("FirstReplace", "test1")
    .Replace("SecondReplace", "test2")
    .Replace("ThirdReplace", "test3")
    .Replace("FourthReplace", "test4")
    .Replace("FifthReplace", "test5");
content = sb.ToString();

或简化您的代码并阅读这些流读者/作者:

File.WriteAllText(
    filePath, 
    File.ReadAllText(path)
        .Replace("FirstReplace", "test1")
        .Replace("SecondReplace", "test2")
        .Replace("ThirdReplace", "test3")
        .Replace("FourthReplace", "test4")
        .Replace("FifthReplace", "test5")
);