tags:

views:

131

answers:

4

Is it possible to change the ConnectionString value in a app.config at runtime? According to the MSDN documentation it should be possible as the ConnectionString property "Gets or sets the connection string."

My code looks like this:

ConnectionStringSettings mainConnection = ConfigurationManager.ConnectionStrings["mainConnection"];
mainConnection.ConnectionString = "Data Source=SERVER;Initial Catalog=" + NewDatabaseName + ";Integrated Security=True";

The error that I receive is this: "Unhandled Exception: System.Configuration.ConfigurationErrorsException: The configuration is read only."

A: 

Not really sure why you would want to constantly change your web.config at runtime (not recommended), but look here for some more information.

Writing to .NET Web.config

The main thing here is that your web.config needs to have read and write permissons for the account that the ASPNET process is running as.

Tommy
+5  A: 
Configuration myConfiguration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); 
    myConfiguration.ConnectionStrings.ConnectionStrings("myDatabaseName").ConnectionString = txtConnectionString.Text; 
    myConfiguration.AppSettings.Settings.Item("myKey").Value = txtmyKey.Text; 
    myConfiguration.Save(); 

Ref: http://www.beansoftware.com/ASP.NET-Tutorials/Modify-Web.Config-Run-Time.aspx

JonH
+1: just a small modification: if you want to re-read the new value from the config file again without the need to restart the application, refresh the file after saving it by calling the following:*System.Configuration.ConfigurationManager.RefreshSection("connectionStrings");*
Sameh Serag
This worked, although I was in a console application so I had to use a different line: Configuration myConfiguration = ConfigurationManager.OpenExeConfiguration(exeFilePath);Note that this does change the physical configuration file.
Matt Connolly
A: 

I'm guessing what you are seeing is a Compiler error, and not a run time error. The class you are using is a generated method from your application settings, and the generated properties only have a getter on the property, and no setter. That's why you receive that error.

To change the property, you need to use the Configuration class, and use the AppSettings property, passing in the string for the key. Then you can call the Configuration.Save method.

Nick
It's a ConnectionStringSetting, not an AppSetting, and it's definitely not a compile error. What's weird is that the documentation says that I can *set* the value.
Matt Connolly
A: 

Changing the connection string using the web.config at runtime is not recommended.
I would suggest maintaining these connections in a different file and implementing a filewatcher to verify if the value of these parameters have changed.

Bharath K