How to Save Configuation in app.config in C# Winforms

一世执手 提交于 2019-11-29 14:19:54

问题


Can someone give me an example of how to save a key/value in app.config using C# and WinForms?


回答1:


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);



回答2:


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");
}



回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!