Reputation: 1233
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."
Upvotes: 11
Views: 10632
Reputation: 1
The connectionStrings-Section is readonly.
I need to change only during session, e.g. database-query with a read-only-account and after validation update/modify-operations with a granted account.
So my solution is a connectionString at appSettings-Section, which can be modified during runtime.
In Web.config:
<appSettings>
<add key="dbconnectionstr" value="Database=...;Host=...;Password=...;Username=..."/>
</appSettings>
At SQLDataSource:
<asp:SqlDataSource ID="datasource1" runat="server" ConnectionString="<%$ AppSettings:dbconnectionstr %>" .... </asp:SqlDataSource>
And at Code:
WebConfigurationManager.AppSettings["dbconnectionstr"] = newonnectionString;
Upvotes: 0
Reputation: 2119
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.
Upvotes: -1
Reputation: 5965
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.
Upvotes: -1
Reputation: 33183
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
Upvotes: 19
Reputation: 39817
Not really sure why you would want to constantly change your web.config at runtime (not recommended), but look here for some more information.
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.
Upvotes: 0