How to Get a Connection String from Web.config

Web.config connection strings can make your ASP.NET application more secure. A connection string contains the parameters needed to connect to a data source such as a SQL database. Because connection strings may contain passwords and other sensitive information, it is wise to store connection string settings in a safe location. An ASP.NET application's web.config file holds these settings. Retrieve them to get the name of any connection string your application needs.

Instructions

    • 1

      Open one of your C# ASP.NET Web projects using Visual Studio. When the Solution Explorer window appears, double-click the web.config file that appears in that window. Visual Studio opens the file in the Code window.

    • 2

      Find the XML tag named <configuration>. Paste the following code below that tag:

      <connectionStrings>
      <add name="CONNECTION STRING NAME"
      connectionString="<CONNECTION STRING>"
      providerName="<PROVIDER>" />
      </connectionStrings>

      Replace "CONNECTION STRING NAME" with the name you would like to give to the connection string. Replace "CONNECTION STRING" with the name of the connection string that accesses your data source. Replace "PROVIDER" with the name of the data source provider.

    • 3

      Return to the Solution Explorer window and right-click the file that generates your project's startup form. Click the View Code option that appears in the drop-down menu. The Code window opens.

    • 4

      Find the Page_Load method that appears in the window and paste the code shown below in the Page_Load method:

      string connectionStringFound;
      string targetConnectionString = "CONNECTION STRING NAME";

      System.Configuration.ConnectionStringSettingsCollection myConnections =
      WebConfigurationManager.ConnectionStrings;

      foreach (System.Configuration.ConnectionStringSettings val in
      myConnections)
      {

      if (val.ConnectionString == targetConnectionString)
      connectionStringFound = val.ConnectionString;

      }

      The first statement defines the variable that will hold your connection string. Replace "CONNECTION STRING NAME" with the name of the connection string you created in the web.config file. The foreach loop loops through the connection strings stored in the web.config file until it finds the one you are looking for. When this code runs, connectionStringFound will contain the desired connection string.

Tips & Warnings

  • This example also retrieves the connection string in the Page_Load method for demonstration purposes. You will probably want to place that code in a separate class or in the method that manages your data connections.

Related Searches:

References

Resources

Comments

Related Ads

Featured