This documentation is archived and is not being maintained.

ConfigurationSectionCollection Class

Represents a collection of related sections within a configuration file.

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

'Declaration
<SerializableAttribute> _
Public NotInheritable Class ConfigurationSectionCollection _
	Inherits NameObjectCollectionBase
'Usage
Dim instance As ConfigurationSectionCollection

Use the ConfigurationSectionCollection class to iterate through a collection of ConfigurationSection objects. You can access this collection of objects using the Sections property or the Sections property.

The ConfigurationSectionCollection class is also used in the creation of custom types that extend the ConfigurationSection class.

The following code example shows how to use the ConfigurationSectionCollection class.

Imports System
Imports System.Configuration
Imports System.Collections




' Define a custom section programmatically. 

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


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

    ' The MasUsers property. 
    Private Shared _MaxUsers _
    As New ConfigurationProperty("maxUsers", _
    GetType(Long), Fix(1000), _
    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



    <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


    <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 




Class UsingCustomSectionCollection


    ' 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 the <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)
            End If 
        Catch err As ConfigurationErrorsException
            Console.WriteLine(err.ToString())
        End Try 
    End Sub 'CreateSection


    Shared Sub GetAllKeys()

        Try 
            Dim config _
            As System.Configuration.Configuration = _
            ConfigurationManager.OpenExeConfiguration( _
            ConfigurationUserLevel.None)


            Dim sections _
            As ConfigurationSectionCollection = _
            config.Sections

            Dim key As String 
            For Each key In sections.Keys
                Console.WriteLine("Key value: {0}", key)
            Next key


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



    Shared Sub Clear()

        Try 
            Dim config _
            As System.Configuration.Configuration = _
            ConfigurationManager.OpenExeConfiguration( _
            ConfigurationUserLevel.None)

            config.Sections.Clear()

            config.Save( _
            ConfigurationSaveMode.Full)
        Catch err As ConfigurationErrorsException
            Console.WriteLine(err.ToString())
        End Try 
    End Sub 'Clear


    Shared Sub GetSection()

        Try 
            Dim customSection _
            As CustomSection = _
            ConfigurationManager.GetSection( _
            "CustomSection")

            If customSection Is Nothing Then
                Console.WriteLine("Failed to load CustomSection.")
            Else 
                ' Display section information
                Console.WriteLine("Defaults:")
                Console.WriteLine("File Name:       {0}", _
                customSection.FileName)
                Console.WriteLine("Max Users:       {0}", _
                customSection.MaxUsers)
                Console.WriteLine("Max Idle Time:   {0}", _
                customSection.MaxIdleTime)
            End If 


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

    Shared Sub GetEnumerator()

        Try 
            Dim config _
            As System.Configuration.Configuration = _
            ConfigurationManager.OpenExeConfiguration( _
            ConfigurationUserLevel.None)

            Dim sections _
            As ConfigurationSectionCollection = _
            config.Sections

            Dim secEnum _
            As IEnumerator = sections.GetEnumerator()

            Dim i As Integer = 0
            While secEnum.MoveNext()
                Dim setionName _
                As String = sections.GetKey(i)
                Console.WriteLine( _
                "Section name: {0}", setionName)
                i += 1
            End While 
        Catch err As ConfigurationErrorsException
            Console.WriteLine(err.ToString())
        End Try 
    End Sub 'GetEnumerator


    Shared Sub GetKeys()

        Try 
            Dim config _
            As System.Configuration.Configuration = _
            ConfigurationManager.OpenExeConfiguration( _
            ConfigurationUserLevel.None)

            Dim sections _
            As ConfigurationSectionCollection = _
            config.Sections


            Dim key As String 
            For Each key In sections.Keys


                Console.WriteLine("Key value: {0}", key)
            Next key


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


    Shared Sub GetItems()

        Try 
            Dim config _
            As System.Configuration.Configuration = _
            ConfigurationManager.OpenExeConfiguration( _
            ConfigurationUserLevel.None)

            Dim sections _
            As ConfigurationSectionCollection = _
            config.Sections


            Dim section1 As ConfigurationSection = _
            sections.Item("runtime")

            Dim section2 As ConfigurationSection = _
            sections.Item(0)

            Console.WriteLine("Section1: {0}", _
            section1.SectionInformation.Name)

            Console.WriteLine("Section2: {0}", _
            section2.SectionInformation.Name)

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


    Shared Sub Remove()

        Try 
            Dim config _
            As System.Configuration.Configuration = _
            ConfigurationManager.OpenExeConfiguration( _
            ConfigurationUserLevel.None)

            Dim customSection As CustomSection = _
            config.GetSection("CustomSection")


            If Not (customSection Is Nothing) Then
                config.Sections.Remove("CustomSection")
                customSection.SectionInformation.ForceSave = True
                config.Save(ConfigurationSaveMode.Full)
            Else
                Console.WriteLine( _
                "CustomSection does not exists.")
            End If 

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


    Shared Sub AddSection()

        Try 
            Dim config _
            As System.Configuration.Configuration = _
            ConfigurationManager.OpenExeConfiguration( _
            ConfigurationUserLevel.None)

            Dim customSection _
            As New CustomSection()


            Dim index As String = _
            config.Sections.Count.ToString()

            customSection.FileName = _
            "newFile" + index + ".txt" 

            Dim sectionName As String = _
            "CustomSection" + index

            Dim ts As New TimeSpan(0, 15, 0)
            customSection.MaxIdleTime = ts
            customSection.MaxUsers = 100

            config.Sections.Add(sectionName, customSection)
            customSection.SectionInformation.ForceSave = True
            config.Save(ConfigurationSaveMode.Full)
        Catch err As ConfigurationErrorsException
            Console.WriteLine(err.ToString())
        End Try 
    End Sub 'AddSection



    ' Exercise the collection. 
    ' Uncomment the function you want to exercise. 
    ' Start with CreateSection(). 
    Public Overloads Shared Sub Main(ByVal args() As String)
        CreateSection()
        ' AddSection() 
        ' GetSection() 
        ' GetEnumerator() 
        ' GetAllKeys() 
        ' GetKeys()
        GetItems()
        ' Clear() 
        ' Remove() 
    End Sub 'Main 

End Class 'UsingCustomSectionCollection 

The following example is an excerpt of the configuration file used by the previous example.

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

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

  </configSections>

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

</configuration>

System.Object
  System.Collections.Specialized.NameObjectCollectionBase
    System.Configuration.ConfigurationSectionCollection

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 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, 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
Show: