Reputation: 2560
I am trying to update the appconfig file on run time with the following code. I do not get an error but it does not update my config file.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
string oldValue = config.AppSettings.Settings["Username"].Value;
config.AppSettings.Settings["Username"].Value = "NewValue";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
Upvotes: 3
Views: 7909
Reputation: 316
You can't update a configuration. You have to remove it and then add it again. This has worked for me, including while debugging through Visual Studio:
config.AppSettings.Settings.Remove("Username");
config.AppSettings.Settings.Add("Username", "NewValue");
config.Save(ConfigurationSaveMode.Modified);
Upvotes: 1
Reputation: 7336
Adding the config.AppSettings.SectionInformation.ForceSave = true;
will do the trick. You should then look in YourProject.vshost.exe.config
when debugging as Justin said. The modifications are saved there.
Upvotes: 3
Reputation: 10330
As long as you have write access to the app.config file the following should work.
// To Save
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["Username"].Value = "NewValue";
config.AppSettings.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Modified);
// To Refresh
ConfigurationManager.RefreshSection("appSettings");
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Upvotes: 1
Reputation: 3397
When I need to update my configuration, I always have to use:
config.AppSettings.SectionInformation.ForceSave = true;
//Save config
//Refresh Config section
Otherwise it doesn't update the configuration file for me.
Also, are you running this in Visual Studio? If you are debugging from Visual Studio, it creates copies int he bin folder so in your actual project, you won't see any changes to the configuration unless you looked at the configuration file in the bin\debug folder.
Upvotes: 0