ASP.NET 2.0 allows storing ConnectionString elements within the ConnectionStrings section in web.config. The web.config section containing ConnectionStrings can be encrypted for security.
ConnectionStrings can be referred via Expressions which are resolved by the ASP.net parser at run-time. When setting the ConnectionString for DataSources, Expressions are typically used to fetch the corresponding ConnectionString element
The ConnectionStrings stored in the web.config's ConnectionStrings section can also be retrieved in code at run-time by using the Configuration object. The correct web.config file needs to be specified in the call to the OpenWebConfiguration() method. The following code snippet shows how to retrieve the ConnectionString element in code, MyWebSite is the name of the website and MyWebDBConnectionString is the name of the ConnectionString element stored in the web.config file.
' Import System.Web
'Retrieve ConnectionString from the web.config ConnectionStrings section
Dim oConfig As System.Configuration.Configuration
Dim strConnectionString As String
oConfig = Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSite")
If (oConfig.ConnectionStrings.ConnectionStrings.Count > 0) Then
strConnectionString = oConfig.ConnectionStrings.ConnectionStrings("MyWebDBConnectionString").ConnectionString
Else
Throw New ApplicationException("Could not load the database")
End If
The above code would be useful if you wanted to retrieve a Connectionstring from web.config for a SQLConnection created manually or if you wanted to save the Connectionstring in the Application variables.
Resources for Encrypting Configuration Sections