如何保存 App.config 中的更改?

How to save changes in App.config?

我正在尝试将设置保存在 App.config 文件中,但我得到的是 InvalidOperationException。我正在关注来自 MSDN.

这是我的代码:

private void button_Update_Click(object sender, EventArgs e)
{
    string Key = textBox_Key.Text.Trim();
    string Value = textBox_Value.Text.Trim();//bug: should use control textBox_NewValue
    if (Key != "" && Value != "")
    {
        try
        {
            // write new value to app.config:
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            KeyValueConfigurationCollection settings = config.AppSettings.Settings;
            if (settings[Key] == null)
                settings.Add(Key, Value);
            else
                settings[Key].Value = Value;
            //config.Save(ConfigurationSaveMode.Modified); //-->Exception: Method failed with unexpected error code 1.
            config.Save(); //-->Exception: Method failed with unexpected error code 1.
            ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
            // feedback:
            textBox_Value.Text = ConfigurationManager.AppSettings[Key];
            textBox_NewValue.Text = "";
        }
        catch (ConfigurationErrorsException exc)
        {
        }//debug breakpoint
        catch (Exception exc)//--> InvalidOperationException
        {
        }//debug breakpoint
    }
    return;
}

当 App.config 之类的文件正在使用并被 运行 应用程序锁定时,可能无法更新该文件?


如下评论,我的问题似乎与 重复。在本地磁盘和/或 运行 .exe 直接(不在 VS 调试模式下)不会发生异常。

不幸的是,我也没有在 App.config 中看到更新的值,但这似乎是一个不相关的问题。


修复我自己的错误后(见上面的评论)我可以确认新值确实写入了非共享磁盘上的文件 {app}。exe.config。

对于 Winforms 项目,当您编译项目时,app.config 文件将作为 <appname>.exe.config 复制到输出目录。对配置所做的任何运行时更改都会对该文件进行(而不是源代码目录中的 app.config)。这是应与您的应用程序一起分发的文件;如果您使用的是 ClickOnce,则此文件将与您的应用程序一起成为部署使用的配置文件。

为了调试目的也值得注意(目前这确实是您的用例),只要您在 Visual Studio 中 运行,实际修改的文件将是 <appname>.vshost.exe.config。您可以通过在 VS 中 运行 并检查 .vshost.exe.config 文件来验证这一点,然后直接从目录中 运行 .exe 并监视 .exe.config 文件。

至于 InvalidOperationException 存在一个已知问题,尽管唯一的解决方案似乎是使用本地目录。