Articles in categories


Change connectionstring and save to app.config

I needed to be able to change my connection string during runtime so I could connect to a different database without have to quit the application, modify the app.config file and restart.

Here's my way how I do this. First you need to add a reference to 'System.Configuration'.

Then I use this method to set or change the connectionstring:

    private static void SetNewConnectionString(string connstringname, string datasource, string initialcatalog, string user, string pwd, string appname)
      // open config
      Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

      // create new connectionString 
      SqlConnectionStringBuilder connbuilder = new SqlConnectionStringBuilder();
      connbuilder.DataSource = datasource;
      connbuilder.InitialCatalog = initialcatalog;
      connbuilder.UserID = user;
      connbuilder.Password = pwd;
      connbuilder.ApplicationName = appname;

      // set new connectionstring in config
      config.ConnectionStrings.ConnectionStrings[connstringname].ConnectionString = connbuilder.ConnectionString;

      // save and refresh the config file

Instead of using the 'SqlConnectionStringBuilder' you can just pass your whole connectionstring in a string value, bu I like to do it this way.

You can call the method like this:

     SetNewConnectionString("ConnectionString", "datasource", "catalog", "user", "pass", "appName");

That's it. Now you can change your connectionstring at runtime.

If you want to read a connectionstring from the app.config file:

ConfigurationManager.ConnectionStrings["connectionstring name"].ConnectionString