0

How is it possible to modify the value of ServerURL of the app.config file on runtime?

Here is the app.config file:

<applicationSettings>
  <SystemVerification.Settings>
    <setting name="ServerURL" serializeAs="String">
      <value>https://linkhere</value>
    </setting>
</applicationSettings>

I tried this:

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        foreach (XmlElement element in xmlDoc.DocumentElement)
        {
            if (element.Name.Equals("applicationSettings"))
            {
                foreach (XmlNode node in element.ChildNodes)
                {
                    if (node.Attributes[0].Name.Equals("ServerURL"))
                    {
                        node.Attributes[1].Value = "New Value";
                    }
                }
            }
        }
        xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        ConfigurationManager.RefreshSection("applicationSettings");
  • 1
    Wouldn't it be easier to mode the setting out of the app.config in the first place? – Esko Feb 19 '18 at 13:43
  • 3
    Possible duplicate of [How to modify my App.exe.config keys at runtime?](https://stackoverflow.com/questions/5468342/how-to-modify-my-app-exe-config-keys-at-runtime) – FaizanHussainRabbani Feb 19 '18 at 13:46
  • I do not think it is a great idea even if it is possible, if your use case is to load a different value of `appSetting` at the runtime, you can create an interface `IAppSettings` and have your own implementation of the interface which takes care of values you supply to your client. – Ankit Vijay Feb 19 '18 at 16:18

0 Answers0