Can someone give me an example of how to save a key/value in app.config using C#
and WinForms?
Edwin Tai
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");
}
Something like this may be : http://geekswithblogs.net/akraus1/articles/64871.aspx
来源:https://stackoverflow.com/questions/1186576/how-to-save-configuation-in-app-config-in-c-sharp-winforms