Programmatically change the connection string in web.config file.

Let’s say you have the below connection string in your web.config file and you need to change that dynamically.

<add name="DefaultConnection"
connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\test.mdf;
Initial Catalog=test;Integrated Security=True"

providerName="System.Data.SqlClient" />

You can use the below code to change the connection string programmatically.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Web.Configuration;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ForumsTest
public partial class WebForm1 : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
ConnectionStringsSection sec = (ConnectionStringsSection)config.GetSection("connectionStrings");
sec.ConnectionStrings["DefaultConnection"].ConnectionString = "Set the connection string here";

On the first line, I’m getting a reference to the web.config file.

On the second line I’m getting the section connectionStrings.

On the third line, I’m getting the specific connection string I want to change. In this example, I’m going to change the connection string named by “DefaultConnection”. Then I set the property value ConnectionString to the new value.

Finally, I’m saving the changes to the configuration.

Keep in mind that editing the web.config file will cause restarting the application pool so think twice before you going in this approach. If you can help it, avoid dynamically changing the web.config file since it’s not a recommended practice in ASP.NET web development.

No comments: