Sdílet prostřednictvím


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.

A Visual Studio project with source code is available to accompany this topic: Download.

Note

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.

Example

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 Not (connString.ConnectionString = Nothing) Then
        Console.WriteLine("Northwind connection string = {0}", connString.ConnectionString)
    Else
        Console.WriteLine("No Northwind connection string")
    End If
End If
         System.Configuration.Configuration rootWebConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
            System.Configuration.ConnectionStringSettings connString;
            if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
            {
                connString =
                    rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"];
                if (connString != null)
                    Console.WriteLine("Northwind connection string = \"{0}\"",
                        connString.ConnectionString);
                else
                    Console.WriteLine("No Northwind connection string");
            }

Compiling the Code

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.

Robust Programming

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.

Security

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.

See Also

Reference

connectionStrings Element (ASP.NET Settings Schema)

ConfigurationSettings