Changing the Web.Config's connectionstring section

Many people ask me how they can change or add a new connectionstring in Web.Config's connectionstring section. Basically you only need import the System.Web.Configuration namespace, open the Web.Config file where is connectionstrings section and change or add a new connectionstring. An example is:

Configuration webConfig = WebConfigurationManager.OpenWebConfiguration("~");
ConnectionStringsSection dbConnString = webConfig.ConnectionStrings;

//Changing
dbConnString.ConnectionStrings["DBOrders"].ConnectionString = "YOUR NEW CONNSTRING HERE";

//Adding
dbConnString.ConnectionStrings.Add(
    new ConnectionStringSettings("MDBTest", "MDB ConnString", "System.Data.OleDb"));

webConfig.Save();

Comments

# re: Changing the Web.Config's connectionstring section

Thursday, September 28, 2006 6:48 AM by ZeCompadre

yes  ! but this is just for .NET 2.0 FrameWork !

any Class like this for 1.1 ?

# re: Changing the Web.Config's connectionstring section

Friday, September 29, 2006 7:10 AM by israel aece

Hello,

In ASP.NET 1.x there isn't the connectionstring section, but I know a class that change the Web.Config or App.Config in runtime: http://www.eggheadcafe.com/articles/20030907.asp

Config's are Xml-based ;)