Compartilhar via


Using the Configuration Classes

Most configuration work is done with the Configuration class. This class represents configurations of computers, .NET client applications, ASP.NET applications, Web directories, and resources that are stored in Web directories.

In ASP.NET version 2.0, you can gain access to an instance of the Configuration class by using the methods of the WebConfigurationManager object to obtain a configuration section. (In .NET Framework client applications, you can use the similar ConfigurationManager object). Each configuration section has its own object type, which is listed as the section handler in the "Element Information" table in the reference topics in ASP.NET Configuration Settings. For an example, see How to: Access ASP.NET Configuration Settings Programmatically.

The following sections describe how to use the configuration classes in different scenarios. For a summary of the configuration classes, see ASP.NET Configuration API Overview.

All of the examples below use the non-static Configuration.GetSection and Configuration.GetSectionGroup methods by creating an instance of the System.Configuration.Configuration class first. 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.

Opening a Configuration Object Mapped to Global Configuration Settings

To open a configuration file for global configuration, your application calls the OpenMachineConfiguration static method of the WebConfigurationManager class. In the following code example, the OpenMachineConfiguration method opens and returns the configuration object that corresponds to the Machine.config file of the .NET Framework 2.0. Other versions of this overloaded method allow you to specify a location, a remote server, or user information.

' Obtains the machine configuration settings on the local machine. 
Dim machineConfig As System.Configuration.Configuration
machineConfig = _
    System.Web.Configuration.WebConfigurationManager.OpenMachineConfiguration()
machineConfig.SaveAs("c:\machineConfig.xml")
         // Obtains the machine configuration settings on the local machine.
            System.Configuration.Configuration machineConfig = 
                System.Web.Configuration.WebConfigurationManager.OpenMachineConfiguration();
            machineConfig.SaveAs("c:\\machineConfig.xml");

The configuration API is version-specific. Therefore, it is not possible to open the Machine.config file for one version of the .NET Framework by using the methods included in another version of the .NET Framework.

Required Privileges

To open the machine configuration file, the application needs Read permission for the physical Machine.config file. To modify the machine configuration, the application needs Write permission for the file, and Create privileges for the .NET Framework configuration directory.

Opening a Configuration Object Mapped to Web-Application Configuration Settings

To open the configuration file for a Web application, your application calls the OpenWebConfiguration static method of the WebConfigurationManager class, passing the relative path of the Internet Information Services (IIS) virtual directory to open.

The values of the path parameter can be obtained from the IIS metabase path of the directory that contains the required configuration. For example, if the IIS metabase path is W3SVC/1/Root/Temp, then the path is /Temp because the default site is 1.

In the following code example, the OpenWebConfiguration method opens and returns the configuration object that corresponds to the Temp Web application in the default Web site. The configuration object includes configuration settings that are specified locally in a Web.config file and all inherited settings from parent configuration files, all the way back to the Machine.config file. Other versions of this overloaded method allow you to specify the Web site, a location, a remote server, and user information.

' Obtains the configuration settings for a Web application. 
Dim webConfig As System.Configuration.Configuration
webConfig = _
    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp")
webConfig.SaveAs("c:\\webConfig.xml")
            // Obtains the configuration settings for a Web application.
            System.Configuration.Configuration webConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp");
            webConfig.SaveAs("c:\\webConfig.xml");

It is possible to open a System.Configuration.Configuration object even when a physical Web.config file does not exist. In this case, the returned configuration consists entirely of settings that are inherited from the configuration file hierarchy. For more information, see ASP.NET Configuration Scenarios.

Required Privileges

To open a Web configuration file, the application needs Read permission for the physical Web.config file, and for all of its parent files in the hierarchy.

Opening a Configuration Object Mapped to a Section in a Configuration File

To obtain configuration information from a section, your application calls the GetSectionGroup non-static method of the Configuration class, passing the section name. For sections that are contained in section groups, you can either use an XPath to the section (system.web/anonymousIdentification), or obtain a configuration object that is mapped to the section group first. For a list of section names, see the ASP.NET Configuration Settings.

In the following code example, the OpenWebConfiguration method opens and returns the configuration object that corresponds to the Temp Web application in the default Web site, and then uses that object to obtain a reference to the system.web section group, which is then used to obtain a reference to the anonymousIdentification section.

' Obtains the configuration settings for the <anonymousIdentification> section. 
Dim config As System.Configuration.Configuration
config = _
    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp")
Dim systemWeb As System.Web.Configuration.SystemWebSectionGroup
systemWeb = config.GetSectionGroup("system.web")
Dim sectionConfig As System.Web.Configuration.AnonymousIdentificationSection
sectionConfig = systemWeb.AnonymousIdentification
Dim sb As New StringBuilder
sb.AppendLine("<anonymousIdentification> attributes:")
Dim props As System.Configuration.PropertyInformationCollection
props = sectionConfig.ElementInformation.Properties
For Each prop As System.Configuration.PropertyInformation In props
    sb.Append(prop.Name.ToString())
    sb.Append(" = ")
    sb.AppendLine(prop.Value.ToString())
Next
Console.WriteLine(sb.ToString())
         // Obtains the configuration settings for the <anonymousIdentification> section.
            System.Configuration.Configuration config =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp");
            System.Web.Configuration.SystemWebSectionGroup systemWeb =
                config.GetSectionGroup("system.web") 
                as System.Web.Configuration.SystemWebSectionGroup;
            System.Web.Configuration.AnonymousIdentificationSection sectionConfig =
                systemWeb.AnonymousIdentification;
            if (sectionConfig != null)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("<anonymousIdentification> attributes:\r\n");
                System.Configuration.PropertyInformationCollection props =
                    sectionConfig.ElementInformation.Properties;
                foreach (System.Configuration.PropertyInformation prop in props)
                {
                    sb.AppendFormat("{0} = {1}\r\n", prop.Name.ToString(), prop.Value.ToString());
                }
                Console.WriteLine(sb.ToString());
            }

It is possible to open a System.Configuration.Configuration object even when a physical Web.config file does not exist. In this case, the returned configuration consists entirely of settings that are inherited from the configuration file hierarchy. For more information, see ASP.NET Configuration Scenarios.

Required Privileges

To open a section in a Web configuration file, the application needs Read permission for the physical Web.config file, and for all of its parent files in the hierarchy. Managed code applications need to have permission to read system sections. Full Trust and High Trust applications have these permissions by default. In other words, by default, medium and lower trust applications will not be able to read configuration sections.

Opening a Configuration Object Mapped to Remote Configuration Settings

You can use the configuration API to open the configuration of a remote computer. The API can open the machine configuration file of another computer, or the application configuration file for any IIS application or its child directories.

To open a machine configuration file on another computer, the application calls the OpenMachineConfiguration static method, passing the name of the server.

To open a Web.config file on another computer, the application calls the OpenWebConfiguration static method, passing the site-relative path to the configuration object, the site identifier, and the name of the server. The returned configuration object includes configuration settings that are specified locally in a Web.config file and all inherited settings from parent configuration files all the way back to the Machine.config file.

Server names are valid Windows networking computer names. These names are not specially handled by ASP.NET but are passed directly to the operating system.

The following code examples show how to open a machine configuration, the root configuration on a default site, and a Web configuration in an application directory.

Dim userToken As IntPtr
userToken = System.Security.Principal.WindowsIdentity.GetCurrent().Token

' Obtains the machine configuration settings on a remote machine. 
Dim remoteMachineConfig As System.Configuration.Configuration
remoteMachineConfig = _
    System.Web.Configuration.WebConfigurationManager.OpenMachineConfiguration( _
    Nothing, "JanetFi2", userToken)
remoteMachineConfig.SaveAs("c:\remoteMachineConfig.xml")

' Obtains the root Web configuration settings on a remote machine. 
Dim remoteRootConfig As System.Configuration.Configuration
remoteRootConfig = _
    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration( _
    Nothing, Nothing, Nothing, "JanetFi2", userToken)
remoteRootConfig.SaveAs("c:\remoteRootConfig.xml")

' Obtains the configuration settings for the  
' W3SVC/1/Root/Temp application on a remote machine. 
Dim remoteWebConfig As System.Configuration.Configuration
remoteWebConfig = _
    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration( _
    "/Temp", "1", Nothing, "JanetFi2", userToken)
remoteWebConfig.SaveAs("c:\\remoteWebConfig.xml")
            IntPtr userToken = System.Security.Principal.WindowsIdentity.GetCurrent().Token;

            // Obtains the machine configuration settings on a remote machine.
            System.Configuration.Configuration remoteMachineConfig =
                System.Web.Configuration.WebConfigurationManager.OpenMachineConfiguration
                (null, "ServerName", userToken);
            remoteMachineConfig.SaveAs("c:\\remoteMachineConfig.xml");

            // Obtains the root Web configuration settings on a remote machine.
            System.Configuration.Configuration remoteRootConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration
                (null, null, null, "ServerName", userToken);
            remoteRootConfig.SaveAs("c:\\remoteRootConfig.xml");

            // Obtains the configuration settings for the  
            // W3SVC/1/Root/Temp application on a remote machine.
            System.Configuration.Configuration remoteWebConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration
                ("/Temp", "1", null, "ServerName", userToken);
            remoteWebConfig.SaveAs("c:\\remoteWebConfig.xml");

Required Privileges

To open a configuration file on a remote computer, the application must have administrative permissions on the remote computer. This requirement is more restrictive than the requirement for local usage. For local configuration files, the application needs only Read permission for the configuration files in the hierarchy and for the IIS metabase (to resolve IIS paths).

Run the Aspnet_regiis.exe tool with the "-config+" parameter on the remote computer before trying to configure it. For more information, see ASP.NET IIS Registration Tool (Aspnet_regiis.exe).

Updating Configuration Settings

To update an open configuration object, the application calls the Save or SaveAs methods of the configuration object. These methods write any configuration setting changes for that object. If a configuration file does not exist at the location, a new configuration file is created.

The following code example sets the debug attribute of the compilation section to true.

' Updates the configuration settings for a Web application. 
Dim updateWebConfig As System.Configuration.Configuration
updateWebConfig = _
    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp")
Dim compilation As System.Web.Configuration.CompilationSection
compilation = _
    updateWebConfig.GetSection("system.web/compilation")
Console.WriteLine("Current <compilation> debug = {0}", compilation.Debug)
compilation.Debug = True 
If Not compilation.SectionInformation.IsLocked Then
    updateWebConfig.Save()
    Console.WriteLine("New <compilation> debug = {0}", compilation.Debug)
Else
    Console.WriteLine("Could not save configuration.")
End If
           // Updates the configuration settings for a Web application.
            System.Configuration.Configuration updateWebConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp");
            System.Web.Configuration.CompilationSection compilation =
                updateWebConfig.GetSection("system.web/compilation") 
                as System.Web.Configuration.CompilationSection;
            Console.WriteLine("Current <compilation> debug = {0}", compilation.Debug);
            compilation.Debug = true;
            if (!compilation.SectionInformation.IsLocked)
            {
                updateWebConfig.Save();
                Console.WriteLine("New <compilation> debug = {0}", compilation.Debug);
            }
            else
            {
                Console.WriteLine("Could not save configuration.");
            }

Currently, there is no functionality available to lock configuration data when updating it. Thus, the configuration API uses an optimistic concurrency model for modifying configuration. Under the optimistic concurrency model, if two applications simultaneously open the same configuration, they will get unique copies of the configuration object. If an application attempts to modify the configuration by calling the Save or SaveAs methods and the underlying configuration file has been modified since the application obtained the configuration object, the method will raise an exception. The underlying file might have been modified by another application updating the configuration, or by some other change to the file independent of the configuration API.

Required Privileges

To modify a Web configuration, the application needs Write permission for the file and Create privileges for the directory that contains the file.

See Also

Concepts

ASP.NET Configuration API Overview

Other Resources

ASP.NET Configuration Settings