2015-05-13 48 views
0

我试图保存在App.config文件中的设置,但我得到InvalidOperationException。我遵循 MSDN的示例。如何保存App.config中的更改?

这是我的代码:

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中看到更新的值,但这似乎是一个无关的问题。


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

+0

'InvalidOperationException'说什么? –

+0

消息是,就像我提到的:'方法失败,出现意外的错误代码1.'并且没有InnerException。确实没什么帮助。 – Roland

+0

尝试添加settings.Remove(key);在添加 – Sachu

回答

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存在已知问题,尽管唯一的解决方案似乎是使用本地目录。

+0

如果您可以将有关共享磁盘的注释添加到您的解决方案中,我会很乐意接受它。 – Roland

+0

@罗兰这是一笔交易 – DrewJordan