Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does changing connection string throw read only error?

I am trying to dynamically set the connection string in web.config in C# code:

ConfigurationManager.ConnectionStrings["ServerConnection"].ConnectionString = "blah";

But it's not allowing me to do it and throwing the following error:

The configuration is read only.

NOTE: I would like to not actually save to web.config if possible. Just dynamically set it in memory.

like image 234
Bill Software Engineer Avatar asked Sep 19 '26 09:09

Bill Software Engineer


1 Answers

var configuration = WebConfigurationManager.OpenWebConfiguration("~");
var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
section.ConnectionStrings["ServerConnection"].ConnectionString = "Data Source=...";
configuration.Save();

If you don't want to change your actual web.config then you can use;

using(OleDbConnection conn = new OleDbConnection("Type here your connection string"))
{
     // Execute my code
}

Or you can copy the value of the connection string to another string if you want to preserve some data then do your changes..

string myNewConnectionString = ConfigurationManager.ConnectionStrings["ServerConnection"].ConnectionString;
myNewConnectionString.Replace("Data Source=Development", "Data Source=Production");
like image 192
asr Avatar answered Sep 21 '26 02:09

asr