我需要添加很多条目到我的web.config文件的许多网站。修改一个web.config文件,就好像它是一个文本文件
我首先查看使用XmlDocument并创建元素和属性,然后将它们插入到文档中。很快,这看起来像是我必须添加的所有元素的大量工作。
将配置文件视为一个长长的文本字符串并在某些位置进行替换以添加我的条目有什么影响。事情是这样的......
private void InsertXMLElement()
{
StringBuilder webConfig = new StringBuilder();
// get the file into a stringbuilder for manipulation
using (var sr = new StreamReader("C:\web.config"))
{
webConfig.Append(sr.ReadToEnd());
}
// insert my element by doing a replace
webConfig.Replace("</configSections>","very long xml element with lots of attributes" + "</configSections>");
}
很明显,我知道文件的手之前的状态,或者可以进行额外检查,以确保该项目已经不存在。