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

Other versions are also available for the following:
.NET Framework 4 - ASP.NET
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.

A Visual Studio project with source code is available to accompany this topic: Using Connection Strings.

Visual Basic
Dim rootWebConfig As System.Configuration.Configuration
    rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot")
Dim connString As System.Configuration.ConnectionStringSettings
If (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0) 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
C#
            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");
            }

This example requires the following:

  • 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
Web.config | Labo4      Dillon Bergkamp   |   Edit   |   Show History
<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
    <system.web>
        <compilation debug="true" strict="false" explicit="true" targetFramework="4.0"/>
        <sessionState mode="InProc" cookieless="true" timeout="5"></sessionState>
        <!--<pages theme="ThemeSilver" />-->
    </system.web>
    <connectionStrings>
      <add name="shop" connectionString="Data Source=(local);Initial Catalog=SportsStore;Persist Security Info=True;User ID=wt3user;Password=kevin"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>
Tags What's this?: Add a tag
Flag as ContentBug
Web.config | Labo3      Dillon Bergkamp   |   Edit   |   Show History
<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
  <connectionStrings>
    <add name="Movies"
         connectionString="Data Source=.;Initial Catalog=Movies;User ID=wt3user;Password=kevin;Integrated Security=SSPI"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

  <system.web>
        <compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
    </system.web>

</configuration>
Tags What's this?: Add a tag
Flag as ContentBug
Two Use Cases: Current Application vs External Application      Rickerj135   |   Edit   |   Show History
The examples using the ConfigurationManager are certainly relevant when trying to read configuration information for the current running web site/application. However, there are cases when an application needs to manage the connection strings from a web.config file from another location.

Configuration conf;
ExeConfigurationFileMap fmap = new ExeConfigurationFileMap();
fmap.ExeConfigFilename = @"C:\AdifferentProject\web.config";
conf = ConfigurationManager.OpenMappedExeConfiguration(fmap, ConfigurationUserLevel.None);
ConnectionStringSettings MyConnSetting = conf.ConnectionStrings.ConnectionStrings["MyDbConnString"];

"MyDbConnString" is the name of a connection string in web.config
Tags What's this?: Add a tag
Flag as ContentBug
Shorter syntax      pointzerotwo   |   Edit   |   Show History
This syntax seems a little easier for reading from the root config file.  (Any downsides vs. the above example?)

string c = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["LeaseFinanceDevContext"].ConnectionString;

(Requires references to System.Web and System.Configuration.)

Tags What's this?: Add a tag
Flag as ContentBug
admin only (web.config) /Security      Joeri Meerdink   |   Edit   |   Show History
<?xml version="1.0"?>
<configuration>
    <system.web>
      <authorization>
        <allow roles="administrator"/>
        <deny users="*"/>
      </authorization>
    </system.web>
</configuration>

// de designer (default.aspx) bevat een loginStatus &;; loginName
   
Tags What's this?: Add a tag
Flag as ContentBug
Example (Web.Config)      Joeri Meerdink   |   Edit   |   Show History
<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
  <connectionStrings>
    <add name="Movies2"
         connectionString="Data Source=(local);Initial Catalog=Movies;User ID=wt3movies;Password=lalalalala;Integrated Security=SSPI"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

  <system.web>
        <compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
    </system.web>

</configuration>
Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2012 Microsoft. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker