Can someone give me an example of how to save a key/value in app.config using C#
and WinForms?
In ASP.NET:
Configuration config = WebConfigurationManager.OpenWebConfiguration(null);
AppSettingsSection app = config.AppSettings;
app.Settings.Add("x", "this is X");
config.Save(ConfigurationSaveMode.Modified);
In WinForms:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;
app.Settings.Add("x", "this is X");
config.Save(ConfigurationSaveMode.Modified);
I know you specifically asked for WinForms solution, but this might help some others. For a .NET 4.0 console application, none of these worked for me. So I used the following and it worked:
private static void UpdateSetting(string key, string value)
{
Configuration configuration = ConfigurationManager.
OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
configuration.AppSettings.Settings[key].Value = value;
configuration.Save();
ConfigurationManager.RefreshSection("appSettings");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With