Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you change the ConnectionString configuration value at runtime?

Tags:

.net

sql

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."

like image 331
Matt Connolly Avatar asked Mar 09 '10 16:03

Matt Connolly


1 Answers

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

like image 102
JonH Avatar answered Oct 22 '22 15:10

JonH