Apr
4
2010
On occasion we may have a request to build out simple little validation tools for testers and or project managers. These types of requests typically require the ability to run the tool against multiple environments; development, QA, stage, and production sometimes. With a configuration file in place, the instance of managing connection strings is very simple with .NET.
The System.Configuration.ConfigurationManager class has all the facilities necessary to make this a reality.
Let’s say our simple little WinForms “validation” app has a combobox where our tester’s can select which environment the validation is to run;

The user can select which environment they would like to use, then click a button, for example. Now, some might digress here and get into a debate on convention over configuration, but this is a silly little sample, a means to an end, which software development is and nothing more… So, that being said, here is what our app.config file may look like. A simple connection string the db for which we are attempting to connect to.
1: <connectionStrings>
2:
3: <add name="MyConnString"
4: connectionString="Data Source=localhost;Initial Catalog=MyDb;Persist Security Info=True;User ID=FakeUser;Password=FakePwd" />
5:
6: </connectionStrings>
Easy-peasy… Now, at runtime we want to be able to alter this setting. The ConfigurationManager class is our hero to the rescue here in 3 lines of code;
1: internal static void SetConnectionStrin(string connectionStringName,string newConnectionStringValue)
2: {
3: var cnfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
4: cnfg.ConnectionStrings.ConnectionStrings[connectionStringName].ConnectionString = newConnectionStringValue;
5: cnfg.Save();
6: ConfigurationManager.RefreshSection("connectionStrings");
7: }
What is important to note here is the call to the RefreshSection method once the change is saved. The reason for this is that when the app is started the configuration is read from the config file into memory for fast access and unless you call this method, you will retrieve stale values after your call to Save().
What is cool about this is here you have an example for not only connection string, but the same can concept can be used for application settings as well. In that instance you would call AppSettings instead of ConnectionStrings of course.
Enjoy!