In .NET applications, Connection Strings are easily stored in and retrieved from a web.config file or an app.config file. Add a
An example is shown below:
"MyApp_Dev"
connectionString="Data Source=Server01;Initial Catalog=AwesomeDB_Dev;Integrated Security=True"/>"MyApp_QA"
connectionString="Data Source=Server01;Initial Catalog=AwesomeDB_QA;Integrated Security=True"/>"MyApp_Prod"
connectionString="Data Source=Server01;Initial Catalog=AwesomeDB;Integrated Security=True"/>
To retrieve a connection string by its associated name attribute, use the utilities found in the System.Configuration namespace of the System.Configuration assembly. First, set a reference to System.Assembly by selecting the menu option Project | Add Reference, selecting the System.Assembly in the Component Name column of the .NET tab of the Add Reference dialog; and, clicking the OK button. Then, add the following using statement to the top of your class file.
This namespace contains the static ConfigurationManager class, which exposes a number of methods for retrieving configuration information. ConfigurationManager.ConnectionStrings returns a collection containing all connection strings settings in the config file of the current assembly. Once we have this collection, we can retrieve a single item by specifying its name. Doing so returns a ConnectionStringSettings object that contains properties retrieved from a single
Sample code is below.
ConnectionStringSettingsCollection cssCollection = ConfigurationManager.ConnectionStrings; ConnectionStringSettings devCsSettings = cssCollection["MyApp_Dev"]; string devCs = devCsSettings.ConnectionString;