1

I have a custom section in the configSections of my App.config file, how can I change the value of one of the variables of this section in code?

The section I would like to change is "serverConfiguration", and I want to change the value of "serverUrl":

<?xml version="1.0" encoding="utf-8"?>
 <configuration>
  <configSections>
   <section name="serverConfiguration" type="someType" />
  </configSections>
    <serverConfiguration serverUrl="http://development/server/" />
</configuration>

I found this piece of code below from this previous question, App.Config change value. It looks close to what I need, but I am not sure how to change it myself to use it for a custom section rather than the AppSettings. Will the code below work for what I am trying to do? How do I change the code below to allow me to pass this new String as serverUrl "http://staging/server/"? Thanks!

class Program
{
    static void Main(string[] args)
    {
        UpdateSetting("lang", "Russian");
    }

    private static void UpdateSetting(string key, string value)
    {
        Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        configuration.AppSettings.Settings[key].Value = value;
        configuration.Save();

        ConfigurationManager.RefreshSection("appSettings");
    }
}
Taylor
  • 81
  • 10

1 Answers1

1

You have an option to load the config into XML, edit the node value and save it back. Give a try with this

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

        xmlDoc.SelectSingleNode("//serverConfiguration").Attributes["serverUrl"].Value = "http://staging/server/";
        xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

Probably, it is a good idea to refresh the Config sections after file is saved.

ConfigurationManager.RefreshSection

Bharathi
  • 1,015
  • 13
  • 41
  • This worked perfect, thank you so much! I've used the Load before with an XML document but did not think to use it in this type of application. – Taylor Jan 14 '19 at 13:25