3

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.

Bill Software Engineer
  • 7,362
  • 23
  • 91
  • 174
  • 1
    Please see [this question](http://stackoverflow.com/questions/2260317/change-a-web-config-programmatically-with-c-sharp-net) for how to change a connection string. – zimdanen Dec 06 '12 at 19:05

2 Answers2

2
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");
asr
  • 716
  • 5
  • 9
  • 2
    Is there anyway to set it in memory only? I don't want to actually make file change. – Bill Software Engineer Dec 06 '12 at 19:10
  • With regard to Project settings files, web-config files and connectionstrings. Remember, the connectionstring is just a string, and can easily be exchanged (in consumer code and settings files) with an ordinary string. Use an ordinary string declared in the scope of the consumer. In Project settings (application scope connectionstrings: make a new string variable in the USER scope. Then it is not readonly. – netfed Sep 27 '13 at 13:57
0

Correct me if I'm wrong but I'm pretty sure that ConfigurationManager configs are meant to be read only. You can change the setting by changing your web.config for app.config.

It's not meant to be set dynamically.

Simon Germain
  • 6,834
  • 1
  • 27
  • 42