【发布时间】: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