Saturday, June 8, 2013

Change Web.config Connection String Properties Dynamically


In certain scenarios you might need to change the connection string properties where you have in the web.config file.

<connectionStrings>
     <add name="GateConnection" connectionString="Data Source=CHAMARA-PC;Initial Catalog=Stock;Integrated Security=True" Password="123" UserID="abc" providerName="System.Data.SqlClient" />
  </connectionStrings>

Using SqlConnectionStringBuilder class you can change the important properties of the connection string dynamically.

public string changeConnection()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["GateConnection"].ConnectionString;
            SqlConnectionStringBuilder conBuilder = new SqlConnectionStringBuilder(connectionString);
            conBuilder.InitialCatalog = "NEW_CATELOG";
            conBuilder.Password = "NEW_PASSWORD";
            conBuilder.UserID = "NEW_USERID";
            return conBuilder.ConnectionString;

        }

Above method will return a connection string something like below.

Data Source=CHAMARA-PC;Initial Catalog=NEW_CATELOG;Integrated Security=True" Password="NEW_PASSWORD" UserID="NEW_USERID" providerName="System.Data.SqlClient

No comments:
Write comments
Recommended Posts × +