Introduction
The application we are developing will be installed at different locations and consequently will need to connect to a local SQL Server instance.
Rather than build separate configurations and installers for every site, we’re planning to store this information centrally. The application then uses a web service to retrieve the appropriate configuration information for its site.
The main problem that needed to be overcome is that .NET doesn’t allow you to change the connection strings after they are read from the app.config file. If you try to do it, it will throw a ConfigurationErrorsException with the message “The configuration is read only”. The following code illustrates this:
- var DBCS = ConfigurationManager.ConnectionStrings[0];
- DBCS.ConnectionString = "data source=srv-suchit; database=student; user id=sa; password=12345";
Here is the code for change connection string Dynamically.
- //Fetch Connection String from Web.config
- // ConnectionStrings[0] == Fetch Connection String Format
- var DBCS = ConfigurationManager.ConnectionStrings[0];
- //Convert Readonly to Writable (In Connection String Provider is readonly so we need to change it as Writable)
- //Dont forgot to Declare BelowNameSpace
- //using System.Configuration;
- //using System.Reflection;
- var writable = typeof(ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
- writable.SetValue(DBCS, false);
- //Replace Connecion string
- DBCS.ConnectionString = "data source=srv-suchit; database=student; user id=sa; password=12345";

Ben BartonPosted Jul 17, 2019, 5:45 AM
Awesome! Helped me to change App.config values dynamically in my win forms app
Nammy KarandePosted Jan 7, 2016, 1:11 AM
Good Article. One quick question : What is 'settings' in this statement : wrt.SetValue(settings, false);
Dhanik SahniPosted Dec 30, 2015, 4:26 AM
Good and helpful
Dhruti ShahPosted Dec 28, 2015, 4:56 AM
Nice one , was having difficulty in Project to change connection string dynamically ,It helped me alot :)
Santhakumar MunuswamyPosted Dec 27, 2015, 9:12 AM
Thanks for sharing