我试图保存在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,非共享磁盘上。
'InvalidOperationException'说什么? –
消息是,就像我提到的:'方法失败,出现意外的错误代码1.'并且没有InnerException。确实没什么帮助。 – Roland
尝试添加settings.Remove(key);在添加 – Sachu