How to: Access ASP.NET Configuration Settings Programmatically

You can access run-time configuration settings from within an ASP.NET application or a .NET client application. Each configuration section has its own object type, which in the case of C# requires a cast when calling the methods of the WebConfigurationManager class. For more information about the object type that is associated with a configuration section, see the section handler in the Element Information table in the reference topics under ASP.NET Configuration Settings.

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

The following code example reads the value of the impersonate attribute of the identity element configured for the MyAppRoot application. The value is displayed on the Web page. The code uses the IdentitySection object type to read the data in the identity section.

To change a configuration setting, use the Save or SaveAs method of the configuration object. For more information, see Using the Configuration Classes.

<%@ Page Language="VB" %>

<%@ Import Namespace="System.Web.Configuration" %>
<%@ Import Namespace="System.Configuration" %>
<%@ Import Namespace="System.Text" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<script runat="server">

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

        ' Set the root path of the Web application that contains the
        ' Web.config file that you want to access.
        Dim configPath As String = "/MyAppRoot"

        ' Get the configuration object to access the related Web.config file.
        Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(configPath)

        ' Get the object related to the <identity> section.
        Dim section As New IdentitySection
        section = config.GetSection("system.web/identity")

        ' Read the <identity> section.
        Dim identity As New StringBuilder
        identity.Append("Impersonate: ")

        ' Display the <identity> information.
        ConfigId.Text = identity.ToString()

    End Sub

<html xmlns="" >
    <title>Read Configuration Settings</title>
        Read ASP.NET Configuration</h2>
        This page displays the value of the <b>Impersonate</b> attribute of the <b>identity</b>
        section of an ASP.NET configuration.
        <asp:Label ID="ConfigId" BackColor="#dcdcdc" BorderWidth="1" runat="Server" /></p>

Community Additions