App.Config Configuration Value Modification
When attempting to modify the value of an App.Config parameter using the following code:
lang = "Russian"; private void Main_FormClosing(object sender, FormClosingEventArgs e) { System.Configuration.ConfigurationManager.AppSettings.Set("lang", lang); }
one may encounter an issue where the modification is not persisted in the App.Config file. To rectify this, it is crucial to avoid the sole use of AppSettings.Set. While AppSettings.Set modifies the value in memory, it does not persist these changes in the configuration file.
To implement a persistent change, one must utilize the following code:
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"); } }
This code snippet includes the following key steps:
When debugging the application, it is important to launch the executable from the output directory rather than the debugger to prevent the App.Config file from being overwritten during each build. The modification can be verified by opening the YourApplicationName.exe.config file in Notepad located in the output directory.
The above is the detailed content of How to Permanently Change App.Config Values in C#?. For more information, please follow other related articles on the PHP Chinese website!