我有一个带有占位符的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();
}
}
有什么建议么
最佳答案
这是因为字符串在.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")
);
关于c# - 在.net 2.0文件中搜索和替换文本。我缺少什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8200795/