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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1186576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:19:26  来源:igfitidea点击:

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

c#configurationapp-config

提问by monkey_boys

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

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

采纳答案by Edwin Tai

In ASP.NET:

ASP.NET 中

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

In WinForms:

WinForms 中

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

回答by Kris-I

回答by Jahmic

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:

我知道您特别要求 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");
}