Search code examples
c#.netweb-configconfigurationmanager

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#?


Solution

  • 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