Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2008
Visual Studio
 How to: Read Connection Strings fro...
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
ASP.NET Configuration
How to: Read Connection Strings from the Web.config File

This example reads a connection string from a Web.config file. The connectionStrings element is a ConnectionStringSettingsCollection collection of ConnectionStringSettings objects. Working with collection elements can be slightly more complicated than working with other configuration elements.

To update a configuration setting, use the Save or SaveAs method of the configuration object. For more information, see Using the Configuration Classes. For additional code examples, see the ConnectionStringsSection class and related classes.

This example uses the non-static method of obtaining configuration data, which allows you to pull configuration information from any application. If you are going to obtain configuration information from the application in which your code resides, use the static method, which processes faster. For more information, see the Working with Local and Remote Configuration Settings section in ASP.NET Configuration API Overview.

NoteNote:

This example applies to a Web site named MyWebSiteRoot. To run the sample, you will have to either run it in a Web site by that name or replace the string supplied to the OpenWebConfiguration method with the name of your Web site.

Visual Basic
Dim rootWebConfig As System.Configuration.Configuration
    rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot")
Dim connString As System.Configuration.ConnectionStringSettings
If (0 < rootWebConfig.ConnectionStrings.ConnectionStrings.Count) Then
    connString = rootWebConfig.ConnectionStrings.ConnectionStrings("NorthwindConnectionString")
    If (Nothing <> connString.ConnectionString) Then
        Console.WriteLine("Northwind connection string = {0}", connString.ConnectionString)
    Else
        Console.WriteLine("No Northwind connection string")
    End If
End If
C#
            System.Configuration.Configuration rootWebConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
            System.Configuration.ConnectionStringSettings connString;
            if (0 < rootWebConfig.ConnectionStrings.ConnectionStrings.Count)
            {
                connString =
                    rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"];
                if (null != connString)
                    Console.WriteLine("Northwind connection string = \"{0}\"",
                        connString.ConnectionString);
                else
                    Console.WriteLine("No Northwind connection string");
            }

This example requires:

  • A connectionStrings element in the root Web.config file that contains a connection named NorthwindConnectionString. The element might look like the following:

    <connectionStrings>
      <add 
        name="NorthwindConnectionString" 
        connectionString="Data Source=serverName;Initial 
        Catalog=Northwind;Persist Security Info=True;User 
        ID=userName;Password=password"
        providerName="System.Data.SqlClient"
      />
    </connectionStrings>
    

    The connectionStrings element is a direct child of the <configuration> element and a peer of the system.web element.

    Security noteSecurity Note:

    When storing sensitive information such as user names and passwords in a configuration file, you should encrypt the sensitive values using protected configuration. For more information, see How To: Secure Connection Strings when Using Data Source Controls.

If the specified connection string does not exist in the Web.config file, no object is returned. When reading connection strings, be sure to check that the code has returned an object.

The configuration file should be protected on the server by using Windows security settings to limit who can read the file. The connectionString element can be encrypted in order to protect it. For details, see Encrypting Configuration Information Using Protected Configuration.

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Possibly an easier method?      A. Stirling   |   Edit   |   Show History

Surely, it is much easier to do the following:

Dim connString As System.Configuration.ConnectionStringSettings =

ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString

Except for...      UncleShooter   |   Edit   |   Show History
It doesn't work... throws and error about "Value 'string' connot be converted to System.Configuration.ConnectionStringSettings "
Tags What's this?: Add a tag
Flag as ContentBug
what he meant was..      eldoran   |   Edit   |   Show History

Dim connString As String =

ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString

The type for connString should be String as ConnectionString is a String value... And setting it this way is clearly easier than the above example.

Simplification For Web Applications      Mark Phillips   |   Edit   |   Show History

using System.Web.Configuration;
string connectionString = WebConfigurationManager.ConnectionStrings["SportsStore"].ConnectionString;

In a web application, the System.Web.dll is referenced by default. This gives you access to the System.Web.Configuration.WebConfigurationManager listed above.

The ConfigurationManager mentioned in the previous comments is good for non-web applications, but unneccessary for web applications. I say unnecessary because in web projects you must manually add a reference to the System.Configuration.dll in order to access its ConfigurationManager. You can avoid this extra step in web projects because System.Web is automatically referenced in web projects - giving you immediate access to the WebConfigurationManager.

if deploying to a web site host (i.e. godaddy site hosting )      webster.net   |   Edit   |   Show History
I tried to use this method when deploying a ASP.NET (MVC) site to godaddy. This led to a file IO exception.

A quick-and-dirty workaround is to statically code your connectionString into your app. Maybe put it in your global.asax or something.

webster.net@live.com
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker