如何保存在App.config中的变化?(How to save changes in App.co

2019-10-23 02:13发布

我想保存设置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()失败 。 在本地磁盘和/或直接运行该.exe(未在VS调试模式)之外不会发生。

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


固定我自己的错误后(见注释以上)我可以证实,新的价值确实写入到文件{}应用.exe.config,非共享磁盘上。

Answer 1:

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

用于调试另外值得注意的(这是真的你的使用情况目前在这里),只要你在Visual Studio中运行,修改了实际的文件将是<appname>.vshost.exe.config 。 您可以通过内部VS运行和检查.vshost.exe.config文件,然后直接运行从目录中的.exe和监测.exe.config文件与验证这一点。

而对于InvalidOperationException ,有一个已知的问题试图访问一个VirtualBox的共享文件夹中的app.config文件 ,但唯一的解决办法似乎是使用本地目录。



文章来源: How to save changes in App.config?