如何在C#Winforms中的app.config中保存配置

时间:2009-07-27 05:44:20

标签: c# configuration app-config

有人能举例说明如何使用C#和WinForms在app.config中保存键/值吗?

3 个答案:

答案 0 :(得分:22)

ASP.NET 中:

Configuration config = WebConfigurationManager.OpenWebConfiguration(null);
AppSettingsSection app = config.AppSettings;
app.Settings.Add("x", "this is X");
config.Save(ConfigurationSaveMode.Modified);

WinForms 中:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;
app.Settings.Add("x", "this is X");
config.Save(ConfigurationSaveMode.Modified);

答案 1 :(得分:1)

我知道你特意要求WinForms解决方案,但这可能对其他人有所帮助。对于.NET 4.0控制台应用程序,这些都不适用于我。所以我使用了以下内容并且有效:

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

答案 2 :(得分:0)