Problem:
An attempt to modify a key-value pair in the App.Config using System.Configuration.ConfigurationManager.AppSettings.Set does not persist the change to the configuration file.
Code:
lang = "Russian"; private void Main_FormClosing(object sender, FormClosingEventArgs e) { System.Configuration.ConfigurationManager.AppSettings.Set("lang", lang); }
Reason:
AppSettings.Set only modifies the configuration settings in memory; it does not update the actual configuration file.
Solution:
To persist the changes, use the UpdateSetting function:
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"); } }
Note:
The above is the detailed content of How Can I Persistently Change App.Config Values in C#?. For more information, please follow other related articles on the PHP Chinese website!