如何在运行时向Web.config添加元素

时间:2017-10-28 03:21:11

标签: c# .net web-config configurationmanager

我知道我可以执行类似下面的操作,以便为AppSettings部分添加密钥:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Add("OS", "Linux");
config.Save(ConfigurationSaveMode.Modified);

ConfigurationManager.RefreshSection("appSettings");

但是我想在<appSettings>节点外添加另一个节点,所以看起来如下所示:

<appSettings>
</appSettings>
<myCustomSetting firstValue="value1" secondValue="value2"/>

我怎样才能在c#中做到这一点?

1 个答案:

答案 0 :(得分:0)

你可以这样做,

var xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

var nodeRegion = xmlDoc.CreateElement("myCustomSetting ");
nodeRegion.SetAttribute("firstValue", "value1");
nodeRegion.SetAttribute("secondValue", "value2");

xmlDoc.SelectSingleNode("//myCustomSetting").AppendChild(nodeRegion);
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

您可以在此处红色 Update custom configuration sections

相关问题