Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 3.5
Configuration Class
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Class Library
Configuration Class

Updated: November 2007

Represents a configuration file applicable to a particular computer, application, or resource. This class cannot be inherited.

Namespace:  System.Configuration
Assembly:  System.Configuration (in System.Configuration.dll)

Visual Basic (Declaration)
Public NotInheritable Class Configuration
Visual Basic (Usage)
Dim instance As Configuration
C#
public sealed class Configuration
Visual C++
public ref class Configuration sealed
J#
public final class Configuration
JScript
public final class Configuration

The Configuration class instance represents the merged view of the configuration settings that apply to a specific physical entity, such as a computer, or to a logical entity, such as an application, or a Web site. The specified logical entity can exist on the local computer or on a remote server.

When no configuration file exists for a specified entity, the Configuration object represents the default configuration settings as defined by the Machine.config file.

You can get a Configuration object using one of the open configuration methods as defined by the following classes:

To generate a configuration file representing the inherited configuration settings for a specified entity, use one of the save-configuration methods:

  • The Save method to create a new configuration file.

  • The SaveAs method to generate a new configuration file at another location.

Note:

To enable access to configuration settings on a remote computer, use the Aspnet_regiis command-line tool. For more information about this tool, see ASP.NET IIS Registration Tool (Aspnet_regiis.exe). For information about creating and accessing custom configuration settings other than the intrinsic sections included in the .NET Framework, refer to ConfigurationSection.

Notes to Implementers:

The Configuration is the class that allows programmatic access for editing configuration files. You use one of the open methods provided by WebConfigurationManager for Web applications or by ConfigurationManager for client applications. These methods will return a Configuration object, which in turn provides the required methods and properties to handle the underlying configuration files. You can access these files for reading or writing as explained next.

You use GetSection or GetSectionGroup to read configuration information. Note that the user or process that reads must have the following permissions:

  • Read permission on the configuration file at the current configuration hierarchy level.

  • Read permissions on all the parent configuration files.

If your application needs read-only access to its own configuration, it is recommended you use the GetSection overloaded methods in case of Web applications. Or the GetSection method in case of client applications.

These methods provide access to the cached configuration values for the current application, which has better performance than the Configuration class.

Note:

If you use a static GetSection method that takes a path parameter, the path parameter must refer to the application in which the code is running, otherwise the parameter is ignored and configuration information for the currently-running application is returned.

You use one of the Save methods to write configuration information. Note that the user or process that writes must have the following permissions:

  • Write permission on the configuration file and directory at the current configuration hierarchy level.

  • Read permissions on all the configuration files.

The following code example demonstrates how to use the Configuration class to create a configuration file containing a custom section.

Visual Basic
' Create a custom section.
Shared Sub CreateSection() 
    Try

        Dim customSection As CustomSection

        ' Get the current configuration file.
        Dim config As _
        System.Configuration.Configuration = _
        ConfigurationManager.OpenExeConfiguration( _
        ConfigurationUserLevel.None)

        ' Create the section entry  
        ' in <configSections> and the 
        ' related target section in <configuration>.
        If config.Sections("CustomSection") Is Nothing Then
            customSection = New CustomSection()
            config.Sections.Add("CustomSection", customSection)
            customSection.SectionInformation.ForceSave = True
            config.Save(ConfigurationSaveMode.Full)

            Console.WriteLine( _
            "Section name: {0} created", _
            customSection.SectionInformation.Name)
        End If

    Catch err As ConfigurationErrorsException
        Console.WriteLine(err.ToString())
    End Try

End Sub 'CreateSection


C#
// Create a custom section.
static void CreateSection()
{
    try
    {

        CustomSection customSection;

        // Get the current configuration file.
        System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

        // Create the section entry  
        // in <configSections> and the 
        // related target section in <configuration>.
        if (config.Sections["CustomSection"] == null)
        {
            customSection = new CustomSection();
            config.Sections.Add("CustomSection", customSection);
            customSection.SectionInformation.ForceSave = true;
            config.Save(ConfigurationSaveMode.Full);

            Console.WriteLine("Section name: {0} created",
                customSection.SectionInformation.Name);

        }
    }
    catch (ConfigurationErrorsException err)
    {
        Console.WriteLine(err.ToString());
    }

}

The following is the definition of the custom section as used by the previous example.

Visual Basic
' Define a custom section.

NotInheritable Public Class CustomSection
    Inherits ConfigurationSection


    Public Enum Permissions
        FullControl = 0
        Modify = 1
        ReadExecute = 2
        Read = 3
        Write = 4
        SpecialPermissions = 5
    End Enum 'Permissions


    Public Sub New() 

    End Sub 'New



    <ConfigurationProperty("fileName", _
    DefaultValue:="default.txt"), _
    StringValidator(InvalidCharacters:=" ~!@#$%^&*()[]{}/;'""|\", _
    MinLength:=1, MaxLength:=60)> _
    Public Property FileName() As String
        Get
            Return CStr(Me("fileName"))
        End Get
        Set(ByVal value As String)
            Me("fileName") = Value
        End Set
    End Property


    <ConfigurationProperty("maxIdleTime", _
    DefaultValue:="1:30:30")> _
    Public Property MaxIdleTime() As TimeSpan
        Get
            Return CType(Me("maxIdleTime"), TimeSpan)
        End Get
        Set(ByVal value As TimeSpan)
            Me("maxIdleTime") = Value
        End Set
    End Property



    <ConfigurationProperty("permission", _
    DefaultValue:=Permissions.Read)> _
    Public Property Permission() As Permissions
        Get
            Return CType(Me("permission"), Permissions)
        End Get

        Set(ByVal value As Permissions)
            Me("permission") = Value
        End Set
    End Property
End Class 'CustomSection


C#
// Define a custom section.
public sealed class CustomSection :
    ConfigurationSection
{

    public enum Permissions
    {
        FullControl = 0,
        Modify = 1,
        ReadExecute = 2,
        Read = 3,
        Write = 4,
        SpecialPermissions = 5
    }

    public CustomSection()
    {

    }

    [ConfigurationProperty("fileName", 
        DefaultValue = "default.txt")]
    [StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;'\"|\\",
               MinLength = 1, MaxLength = 60)]
    public String FileName
    {
        get
        {
            return (String)this["fileName"];
        }
        set
        {
            this["fileName"] = value;
        }
    }

    [ConfigurationProperty("maxIdleTime", DefaultValue="1:30:30")]
    public TimeSpan MaxIdleTime
    {
        get
        {
            return (TimeSpan)this["maxIdleTime"];
        }
        set
        {
            this["maxIdleTime"] = value;
        }
    }


    [ConfigurationProperty("permission", 
        DefaultValue = Permissions.Read)]
    public Permissions Permission
    {
        get
        {
            return (Permissions)this["permission"];
        }

        set
        {
            this["permission"] = value;
        }

    }

}

The following is a configuration excerpt as used by the previous example.

<?xml version="1.0" encoding="utf-8"?>

<configuration>

  <configSections>
    <section name="CustomSection" type="Samples.AspNet.CustomSection, 
      Configuration, Version=1.0.0.0, Culture=neutral, 
      PublicKeyToken=null" allowDefinition="Everywhere" 
      allowExeDefinition="MachineToApplication" 
      restartOnExternalChanges="true" />
  </configSections>
    <CustomSection fileName="default.txt" maxIdleTime="01:30:30"
      permission="Read" />

</configuration>
System..::.Object
  System.Configuration..::.Configuration
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2008 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker