I was running into a problem when trying to modify the app.config file for an application at runtime. Specifically, I was adding connection strings to the <connectionStrings> section but further along in my code the changes were not visible. However, the configuration file was changed! How could this be? After much head scratching and research, I find the problem.
To change the app.config file I was opening the config file like this:
System.Configuration.
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
I then add or update individual connection strings as need (that code's not important). Finally, I save the changes:
config.Save(System.Configuration.
ConfigurationSaveMode.Modified);
Further on in the code I then attempt to access the connection strings, but instead I use the ConfigurationManager class like this:
ConnectionStringSettings
dbConn = System.Configuration.ConfigurationManager.ConnectionStrings[DefaultDatabaseKey];
The problem is that the ConfigurationManager - which is a static class - already has a stored copy of the configuration file in its internals. The answer is to call RefreshSection("...") after saving changes to the config file:
config.Save(System.Configuration.
ConfigurationSaveMode.Modified);
System.Configuration.ConfigurationManager.RefreshSection("connectionStrings");