简体   繁体   中英

How to set connectionstring at web.config file programmatically or dynamically?

I'm trying to create an ASP.NET website. There I'm using a database. To connect with the database I'm using the connectionstring which I've stored in the web.config file like

  <connectionStrings>
  <add name="DBConnectionString" 
    connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=G:\CarRentalServices\App_Data\CarRentalServiceDB.mdf;Integrated Security=True"/>
  </connectionStrings>

and at code behind

private string _connectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;

So you can see the database is stored at G:\\path\\to\\db\\CarRentalServiceDB.mdf .

But now if my friend want to take the project from me and try to run the project from his machine then he has to change the connectionString at web.config . Say the website is now at D:\\path\\to\\db\\foo\\CarRentalServiceDB.mdf in my friend's machine, then the connectionString needs to change. Isn't it tedious?

Is there any way to change the connectionString dynamically with any batch file or code so that it will change with respect to the current directory it is residing now?

You shoud use the |DataDirectory| token: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx

<connectionStrings>
 <add name="DBConnectionString" 
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\App_Data\CarRentalServiceDB.mdf;Integrated Security=True"/>

You would add multiple connections strings in your web.config file and call the one you need like

Web.config File

  <connectionStrings>
  <add name="DBConnectionString" 
    connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=G:\CarRentalServices\App_Data\CarRentalServiceDB.mdf;Integrated Security=True"/>
  <add name="DBConnectionStringTwo" 
    connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\path\to\db\foo\CarRentalServiceDB.mdf;Integrated Security=True"/>
  </connectionStrings>

Code for connection strings

//Connection String 1 
private string _connectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;

//Connection String 2 
private string _connectionString2 = ConfigurationManager.ConnectionStrings["DBConnectionStringTwo"].ConnectionString;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM