【问题标题】:How to save changes in App.config?如何保存 App.config 中的更改?
【发布时间】:2015-05-18 21:56:53
【问题描述】:

我正在尝试将设置保存在 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 之类的文件正在使用并被正在运行的应用程序锁定时,是否可能无法更新该文件?


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

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


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

【问题讨论】:

  • InvalidOperationException 说什么?
  • 消息是,就像我提到的:Method failed with unexpected error code 1. 并且没有 InnerException。确实没有多大帮助。
  • 尝试添加 settings.Remove(key);添加前
  • @Sachu 感谢您的建议。但是,我刚刚试了一下,还是出现了同样的异常。
  • 配置文件是在网络驱动器上还是本地机器上?

标签: c# winforms configuration


【解决方案1】:

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

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

至于InvalidOperationExceptiontrying to access the app.config file in a VirtualBox shared folder 存在一个已知问题,尽管唯一的解决方案似乎是使用本地目录。

【讨论】:

  • 如果您可以将您对共享磁盘的评论添加到您的解决方案中,我很乐意接受。
猜你喜欢
  • 2015-08-02
  • 2016-08-07
  • 2016-03-25
  • 1970-01-01
  • 1970-01-01
  • 2011-04-07
  • 1970-01-01
  • 2014-09-22
  • 2010-11-14
相关资源
最近更新 更多