Skip to main content
.NET Framework Class Library
ConfigurationSection Class

Represents a section within a configuration file.

Inheritance Hierarchy
SystemObject
   System.ConfigurationConfigurationElement
    System.ConfigurationConfigurationSection
      More...

Namespace:   System.Configuration
Assembly:  System.Configuration (in System.Configuration.dll)
Syntax
Public MustInherit Class ConfigurationSection _
	Inherits [%$TOPIC/x0kca287_en-us_VS_110_2_0_0_0_0%]
public abstract class ConfigurationSection : [%$TOPIC/x0kca287_en-us_VS_110_2_0_1_0_0%]
public ref class ConfigurationSection abstract : public [%$TOPIC/x0kca287_en-us_VS_110_2_0_2_0_0%]
[<[%$TOPIC/x0kca287_en-us_VS_110_2_0_3_0_0%]>]
type ConfigurationSection =  
    class 
        inherit [%$TOPIC/x0kca287_en-us_VS_110_2_0_3_0_1%] 
    end

The ConfigurationSection type exposes the following members.

Constructors
  NameDescription
Protected method ConfigurationSectionInitializes a new instance of the ConfigurationSection class.
Top
Properties
  NameDescription
Public property CurrentConfigurationGets a reference to the top-level Configuration instance that represents the configuration hierarchy that the current ConfigurationElement instance belongs to. (Inherited from ConfigurationElement.)
Public property ElementInformationGets an ElementInformation object that contains the non-customizable information and functionality of the ConfigurationElement object. (Inherited from ConfigurationElement.)
Protected property ElementPropertyGets the ConfigurationElementProperty object that represents the ConfigurationElement object itself. (Inherited from ConfigurationElement.)
Protected property EvaluationContextGets the ContextInformation object for the ConfigurationElement object. (Inherited from ConfigurationElement.)
Protected property HasContextGets a value that indicates whether the CurrentConfiguration property is . (Inherited from ConfigurationElement.)
Protected property ItemConfigurationPropertyGets or sets a property or attribute of this configuration element. (Inherited from ConfigurationElement.)
Protected property ItemStringGets or sets a property, attribute, or child element of this configuration element. (Inherited from ConfigurationElement.)
Public property LockAllAttributesExceptGets the collection of locked attributes. (Inherited from ConfigurationElement.)
Public property LockAllElementsExceptGets the collection of locked elements. (Inherited from ConfigurationElement.)
Public property LockAttributesGets the collection of locked attributes (Inherited from ConfigurationElement.)
Public property LockElementsGets the collection of locked elements. (Inherited from ConfigurationElement.)
Public property LockItemGets or sets a value indicating whether the element is locked. (Inherited from ConfigurationElement.)
Protected property PropertiesGets the collection of properties. (Inherited from ConfigurationElement.)
Public property SectionInformationGets a SectionInformation object that contains the non-customizable information and functionality of the ConfigurationSection object.
Top
Methods
  NameDescription
Protected method DeserializeElementReads XML from the configuration file. (Inherited from ConfigurationElement.)
Protected method DeserializeSectionInfrastructure. Reads XML from the configuration file.
Public method EqualsCompares the current ConfigurationElement instance to the specified object. (Inherited from ConfigurationElement.)
Protected method FinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method GetHashCodeGets a unique value representing the current ConfigurationElement instance. (Inherited from ConfigurationElement.)
Protected method GetRuntimeObjectReturns a custom object when overridden in a derived class.
Protected method GetTransformedAssemblyStringReturns the transformed version of the specified assembly name. (Inherited from ConfigurationElement.)
Protected method GetTransformedTypeStringReturns the transformed version of the specified type name. (Inherited from ConfigurationElement.)
Public method GetTypeGets the Type of the current instance. (Inherited from Object.)
Protected method InitSets the ConfigurationElement object to its initial state. (Inherited from ConfigurationElement.)
Protected method InitializeDefaultUsed to initialize a default set of values for the ConfigurationElement object. (Inherited from ConfigurationElement.)
Protected method IsModifiedIndicates whether this configuration element has been modified since it was last saved or loaded when implemented in a derived class. (Overrides ConfigurationElementIsModified.)
Public method IsReadOnlyGets a value indicating whether the ConfigurationElement object is read-only. (Inherited from ConfigurationElement.)
Protected method ListErrorsAdds the invalid-property errors in this ConfigurationElement object, and in all subelements, to the passed list. (Inherited from ConfigurationElement.)
Protected method MemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected method OnDeserializeUnrecognizedAttributeGets a value indicating whether an unknown attribute is encountered during deserialization. (Inherited from ConfigurationElement.)
Protected method OnDeserializeUnrecognizedElementGets a value indicating whether an unknown element is encountered during deserialization. (Inherited from ConfigurationElement.)
Protected method OnRequiredPropertyNotFoundThrows an exception when a required property is not found. (Inherited from ConfigurationElement.)
Protected method PostDeserializeCalled after deserialization. (Inherited from ConfigurationElement.)
Protected method PreSerializeCalled before serialization. (Inherited from ConfigurationElement.)
Protected method ResetResets the internal state of the ConfigurationElement object, including the locks and the properties collections. (Inherited from ConfigurationElement.)
Protected method ResetModifiedResets the value of the IsModified method to false when implemented in a derived class. (Overrides ConfigurationElementResetModified.)
Protected method SerializeElementWrites the contents of this configuration element to the configuration file when implemented in a derived class. (Inherited from ConfigurationElement.)
Protected method SerializeSectionInfrastructure. Creates an XML string containing an unmerged view of the ConfigurationSection object as a single section to write to a file.
Protected method SerializeToXmlElementWrites the outer tags of this configuration element to the configuration file when implemented in a derived class. (Inherited from ConfigurationElement.)
Protected method SetPropertyValueSets a property to the specified value. (Inherited from ConfigurationElement.)
Protected method SetReadOnlySets the IsReadOnly property for the ConfigurationElement object and all subelements. (Inherited from ConfigurationElement.)
Protected method ShouldSerializeElementInTargetVersionIndicates whether the specified element should be serialized when the configuration object hierarchy is serialized for the specified target version of the .NET Framework.
Protected method ShouldSerializePropertyInTargetVersionIndicates whether the specified property should be serialized when the configuration object hierarchy is serialized for the specified target version of the .NET Framework.
Protected method ShouldSerializeSectionInTargetVersionIndicates whether the current ConfigurationSection instance should be serialized when the configuration object hierarchy is serialized for the specified target version of the .NET Framework.
Public method ToStringReturns a string that represents the current object. (Inherited from Object.)
Protected method UnmergeModifies the ConfigurationElement object to remove all values that should not be saved. (Inherited from ConfigurationElement.)
Top
Remarks

You use the ConfigurationSection class to implement a custom section type. Extend the ConfigurationSection class to provide custom handling and programmatic access to custom configuration sections. For information about how use custom configuration sections, see How to: Create Custom Configuration Sections Using ConfigurationSection.

A section registers its handling type with an entry in the configSections element. For an example, see the configuration file excerpt shown in the Example section.

NoteNote

In previous versions of the .NET Framework, configuration section handlers were used to make changes to configuration settings programmatically. Now, all the default configuration sections are represented by classes that extend the ConfigurationSection class.

Notes to Implementers

You can use a programmatic or a declarative (attributed) coding model to create custom configuration sections:

  • Programmatic model. This model requires that for each section attribute you create a property to get or set its value and add it to the internal property bag of the underlying ConfigurationElement base class.

  • Declarative model. This simpler model, also called the attributed model, allows you to define a section attribute by using a property and decorating it with attributes. These attributes instruct the ASP.NET configuration system about the property types and their default values. With this information, obtained through reflection, the ASP.NET configuration system creates the section property objects and performs the required initialization.

The Configuration class allows programmatic access for editing configuration files. You can access these files for reading or writing as follows:

  • Reading. 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 the case of Web applications, or the ConfigurationManagerGetSection method in the 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.

    NoteNote

    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.

  • Writing. 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.

Examples

The following example shows how to implement a custom section programmatically.

For a complete example that shows how to implement and use a custom section implemented using the attributed model, see ConfigurationElement.

' Define a custom section. 
' The CustomSection type allows to define a custom section  
' programmatically. 

NotInheritable Public Class CustomSection
   Inherits ConfigurationSection
   ' The collection (property bag) that contains  
   ' the section properties. 
   Private Shared _Properties As ConfigurationPropertyCollection

   ' Internal flag to disable  
   ' property setting. 
   Private Shared _ReadOnly As Boolean 

   ' The FileName property. 
    Private Shared _FileName As New ConfigurationProperty( _
    "fileName", GetType(String), _
    "default.txt", _
    ConfigurationPropertyOptions.IsRequired)

   ' The MaxUsers property. 
    Private Shared _MaxUsers As New ConfigurationProperty( _
    "maxUsers", GetType(Long), _
    CType(1000, Long), _
    ConfigurationPropertyOptions.None)

   ' The MaxIdleTime property. 
    Private Shared _MaxIdleTime As New ConfigurationProperty( _
    "maxIdleTime", GetType(TimeSpan), _
    TimeSpan.FromMinutes(5), _
    ConfigurationPropertyOptions.IsRequired)


   ' CustomSection constructor. 
   Public Sub New()
      ' Property initialization
        _Properties = _
        New ConfigurationPropertyCollection()

      _Properties.Add(_FileName)
      _Properties.Add(_MaxUsers)
      _Properties.Add(_MaxIdleTime)
   End Sub 'New 


   ' This is a key customization.  
   ' It returns the initialized property bag. 
    Protected Overrides ReadOnly Property Properties() _
    As ConfigurationPropertyCollection
        Get 
            Return _Properties
        End Get 
    End Property 



   Private Shadows ReadOnly Property IsReadOnly() As Boolean 
      Get 
         Return _ReadOnly
      End Get 
   End Property 


   ' Use this to disable property setting. 
   Private Sub ThrowIfReadOnly(propertyName As String)
      If IsReadOnly Then 
            Throw New ConfigurationErrorsException( _
            "The property " + propertyName + " is read only.")
      End If 
   End Sub 'ThrowIfReadOnly



   ' Customizes the use of CustomSection 
    ' by setting _ReadOnly to false. 
   ' Remember you must use it along with ThrowIfReadOnly. 
   Protected Overrides Function GetRuntimeObject() As Object 
      ' To enable property setting just assign true to 
      ' the following flag.
      _ReadOnly = True 
      Return MyBase.GetRuntimeObject()
   End Function 'GetRuntimeObject


    <StringValidator( _
    InvalidCharacters:=" ~!@#$%^&*()[]{}/;'""|\", _
    MinLength:=1, MaxLength:=60)> _
    Public Property FileName() As String 
        Get 
            Return CStr(Me("fileName"))
        End Get 
        Set(ByVal value As String)
            ' With this you disable the setting. 
            ' Remember that the _ReadOnly flag must 
            ' be set to true in the GetRuntimeObject.
            ThrowIfReadOnly("FileName")
            Me("fileName") = value
        End Set 
    End Property


    <LongValidator( _
    MinValue:=1, MaxValue:=1000000, _
    ExcludeRange:=False)> _
    Public Property MaxUsers() As Long 
        Get 
            Return Fix(Me("maxUsers"))
        End Get 
        Set(ByVal value As Long)
            Me("maxUsers") = Value
        End Set 
    End Property


    <TimeSpanValidator( _
    MinValueString:="0:0:30", _
    MaxValueString:="5:00:0", ExcludeRange:=False)> _
    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 
End Class 'CustomSection 
// Define a custom section. 
// The CustomSection type allows to define a custom section  
// programmatically. 
public sealed class CustomSection : 
    ConfigurationSection
{
    // The collection (property bag) that contains  
    // the section properties. 
    private static ConfigurationPropertyCollection _Properties;

    // Internal flag to disable  
    // property setting. 
    private static bool _ReadOnly;

    // The FileName property. 
    private static readonly ConfigurationProperty _FileName =
        new ConfigurationProperty("fileName", 
        typeof(string),"default.txt", 
        ConfigurationPropertyOptions.IsRequired);

    // The MaxUsers property. 
    private static readonly ConfigurationProperty _MaxUsers =
        new ConfigurationProperty("maxUsers", 
        typeof(long), (long)1000, 
        ConfigurationPropertyOptions.None);

    // The MaxIdleTime property. 
    private static readonly ConfigurationProperty _MaxIdleTime =
        new ConfigurationProperty("maxIdleTime", 
        typeof(TimeSpan), TimeSpan.FromMinutes(5), 
        ConfigurationPropertyOptions.IsRequired);

    // CustomSection constructor. 
    public CustomSection()
    {
        // Property initialization
        _Properties = 
            new ConfigurationPropertyCollection();

        _Properties.Add(_FileName);
        _Properties.Add(_MaxUsers);
        _Properties.Add(_MaxIdleTime);
   }


    // This is a key customization.  
    // It returns the initialized property bag. 
    protected override ConfigurationPropertyCollection Properties
    {
        get
        {
            return _Properties;
        }
    }


    private new bool IsReadOnly
    {
        get
        {
            return _ReadOnly;
        }
    }

    // Use this to disable property setting. 
    private void ThrowIfReadOnly(string propertyName)
    {
        if (IsReadOnly)
            throw new ConfigurationErrorsException(
                "The property " + propertyName + " is read only.");
    }


    // Customizes the use of CustomSection 
    // by setting _ReadOnly to false. 
    // Remember you must use it along with ThrowIfReadOnly. 
    protected override object GetRuntimeObject()
    {
        // To enable property setting just assign true to 
        // the following flag.
        _ReadOnly = true;
        return base.GetRuntimeObject();
    }


    [StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;'\"|\\",
        MinLength = 1, MaxLength = 60)]
    public string FileName
    {
        get
        {
            return (string)this["fileName"];
        }
        set
        {
            // With this you disable the setting. 
            // Remember that the _ReadOnly flag must 
            // be set to true in the GetRuntimeObject.
            ThrowIfReadOnly("FileName");
            this["fileName"] = value;
        }
    }

    [LongValidator(MinValue = 1, MaxValue = 1000000,
        ExcludeRange = false)]
    public long MaxUsers
    {
        get
        {
            return (long)this["maxUsers"];
        }
        set
        {
            this["maxUsers"] = value;
        }
    }

    [TimeSpanValidator(MinValueString = "0:0:30",
        MaxValueString = "5:00:0",
        ExcludeRange = false)]
    public TimeSpan MaxIdleTime
    {
        get
        {
            return  (TimeSpan)this["maxIdleTime"];
        }
        set
        {
            this["maxIdleTime"] = value;
        }
    }


}

The following example is an excerpt of the configuration file as it applies to the previous example.

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

<configuration>

<configSections>

<section name="CustomSection" type="Samples.AspNet. CustomSection, CustomConfigurationSection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" restartOnExternalChanges="true" />

</configSections>

<CustomSection fileName="default.txt" maxUsers="1000" maxIdleTime="00:15:00" />

</configuration>

Version Information

.NET Framework

Supported in: 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
Platforms

Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

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

Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Inheritance Hierarchy
SystemObject
   System.ConfigurationConfigurationElement
    System.ConfigurationConfigurationSection
       System.ConfigurationAppSettingsSection
       System.ConfigurationClientSettingsSection
       System.ConfigurationConnectionStringsSection
       System.ConfigurationDefaultSection
       System.ConfigurationIgnoreSection
       System.ConfigurationProtectedConfigurationSection
       System.ConfigurationUriSection
       System.Data.Services.ConfigurationDataServicesFeaturesSection
       System.Drawing.ConfigurationSystemDrawingSection
       System.IdentityModel.ConfigurationSystemIdentityModelSection
       System.IdentityModel.Services.ConfigurationSystemIdentityModelServicesSection
       System.Net.ConfigurationAuthenticationModulesSection
       System.Net.ConfigurationConnectionManagementSection
       System.Net.ConfigurationDefaultProxySection
       System.Net.ConfigurationRequestCachingSection
       System.Net.ConfigurationSettingsSection
       System.Net.ConfigurationSmtpSection
       System.Net.ConfigurationWebRequestModulesSection
       System.Runtime.Caching.ConfigurationMemoryCacheSection
       System.Runtime.Serialization.ConfigurationDataContractSerializerSection
       System.Runtime.Serialization.ConfigurationNetDataContractSerializerSection
       System.ServiceModel.Activation.ConfigurationDiagnosticSection
       System.ServiceModel.Activation.ConfigurationNetPipeSection
       System.ServiceModel.Activation.ConfigurationNetTcpSection
       System.ServiceModel.Activities.ConfigurationWorkflowHostingOptionsSection
       System.ServiceModel.Activities.Tracking.ConfigurationTrackingSection
       System.ServiceModel.ConfigurationBehaviorsSection
       System.ServiceModel.ConfigurationBindingsSection
       System.ServiceModel.ConfigurationClientSection
       System.ServiceModel.ConfigurationComContractsSection
       System.ServiceModel.ConfigurationCommonBehaviorsSection
       System.ServiceModel.ConfigurationDiagnosticSection
       System.ServiceModel.ConfigurationExtensionsSection
       System.ServiceModel.ConfigurationProtocolMappingSection
       System.ServiceModel.ConfigurationServiceHostingEnvironmentSection
       System.ServiceModel.ConfigurationServicesSection
       System.ServiceModel.ConfigurationStandardEndpointsSection
       System.ServiceModel.Routing.ConfigurationRoutingSection
       System.Transactions.ConfigurationDefaultSettingsSection
       System.Transactions.ConfigurationMachineSettingsSection
       System.Web.ConfigurationAnonymousIdentificationSection
       System.Web.ConfigurationAuthenticationSection
       System.Web.ConfigurationAuthorizationSection
       System.Web.ConfigurationCacheSection
       System.Web.ConfigurationClientTargetSection
       System.Web.ConfigurationCompilationSection
       System.Web.ConfigurationCustomErrorsSection
       System.Web.ConfigurationDeploymentSection
       System.Web.ConfigurationFullTrustAssembliesSection
       System.Web.ConfigurationGlobalizationSection
       System.Web.ConfigurationHealthMonitoringSection
       System.Web.ConfigurationHostingEnvironmentSection
       System.Web.ConfigurationHttpCookiesSection
       System.Web.ConfigurationHttpHandlersSection
       System.Web.ConfigurationHttpModulesSection
       System.Web.ConfigurationHttpRuntimeSection
       System.Web.ConfigurationIdentitySection
       System.Web.ConfigurationMachineKeySection
       System.Web.ConfigurationMembershipSection
       System.Web.ConfigurationOutputCacheSection
       System.Web.ConfigurationOutputCacheSettingsSection
       System.Web.ConfigurationPagesSection
       System.Web.ConfigurationPartialTrustVisibleAssembliesSection
       System.Web.ConfigurationProcessModelSection
       System.Web.ConfigurationProfileSection
       System.Web.ConfigurationProtocolsSection
       System.Web.ConfigurationRoleManagerSection
       System.Web.ConfigurationScriptingAuthenticationServiceSection
       System.Web.ConfigurationScriptingJsonSerializationSection
       System.Web.ConfigurationScriptingProfileServiceSection
       System.Web.ConfigurationScriptingRoleServiceSection
       System.Web.ConfigurationScriptingScriptResourceHandlerSection
       System.Web.ConfigurationSecurityPolicySection
       System.Web.ConfigurationSessionPageStateSection
       System.Web.ConfigurationSessionStateSection
       System.Web.ConfigurationSiteMapSection
       System.Web.ConfigurationSqlCacheDependencySection
       System.Web.ConfigurationTraceSection
       System.Web.ConfigurationTrustSection
       System.Web.ConfigurationUrlMappingsSection
       System.Web.ConfigurationWebControlsSection
       System.Web.ConfigurationWebPartsSection
       System.Web.ConfigurationXhtmlConformanceSection
       System.Web.MobileDeviceFiltersSection
       System.Web.Services.ConfigurationWebServicesSection
       System.Web.UI.MobileControlsMobileControlsSection
       System.Windows.FormsWindowsFormsSection
       System.Workflow.Activities.ConfigurationActiveDirectoryRoleFactoryConfiguration
       System.Workflow.ActivitiesExternalDataExchangeServiceSection
       System.Workflow.Runtime.ConfigurationWorkflowRuntimeSection
       System.Xaml.Hosting.ConfigurationXamlHostingSection
       System.Xml.Serialization.ConfigurationDateTimeSerializationSection
       System.Xml.Serialization.ConfigurationSchemaImporterExtensionsSection
       System.Xml.Serialization.ConfigurationXmlSerializerSection
       System.Xml.XmlConfigurationXmlReaderSection
       System.Xml.XmlConfigurationXsltConfigSection