简体   繁体   中英

How to add elements to Web.config at runtime

I know that I can do something like below in order to add keys to AppSettings section:

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

ConfigurationManager.RefreshSection("appSettings");

but I would like to add another node right outside <appSettings> node so it looks something like below:

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

How can I do this in c#?

You can do this,

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);

You can red here Update custom configuration sections

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM