I am trying to save settings in the App.config file, but am getting InvalidOperationException. I am following the example from MSDN.
This is my code:
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; } Might there be something that it is not possible to update a file like App.config while it is in use and locked by the running application?
As commented below, my question seems a duplicate of ConfigurationManager.save() fails. On a local disk and / or running the .exe directly (not in VS Debug mode) the exception does not occur.
Unfortunately, I do also not see an updated value in App.config, but that seems an unrelated question.
After fixing my own bug (see comment above) I can confirm that the new value is indeed written, to the file {app}.exe.config, on a non-shared disk.
InvalidOperationExceptionsay?Method failed with unexpected error code 1.and there was no InnerException. Not much help indeed.