我想保存设置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,非共享磁盘上。