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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With