Changing App.config at Runtime

后端 未结 4 1986
旧时难觅i
旧时难觅i 2020-12-01 13:29

I\'m writing a test WinForms / C# / .NET 3.5 application for the system we\'re developing and we fell in the need to switch between .config files at runtime, but this is tur

4条回答
  •  伪装坚强ぢ
    2020-12-01 14:11

    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.

提交回复
热议问题