Changing App.config at Runtime

I understand this is quite an old thread, but I could not get the listed methods to work. Here is a simpler version of the UpdateAppSettings method (using .NET 4.0):

private void UpdateAppSettings(string theKey, string theValue)
        {
            Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (ConfigurationManager.AppSettings.AllKeys.Contains(theKey))
            {
                configuration.AppSettings.Settings[theKey].Value = theValue;
            }

            configuration.Save(ConfigurationSaveMode.Modified);

            ConfigurationManager.RefreshSection("appSettings");
        }

Pretty readable and avoids having to traverse the app.config using Xpath or the like.
Note: The code above is inspired from this snippet on MSDN.

Leave a Comment