ConfigurationSectionCollection 類別

定義

代表組態檔內相關區段的集合。

public ref class ConfigurationSectionCollection sealed : System::Collections::Specialized::NameObjectCollectionBase
public sealed class ConfigurationSectionCollection : System.Collections.Specialized.NameObjectCollectionBase
[System.Serializable]
public sealed class ConfigurationSectionCollection : System.Collections.Specialized.NameObjectCollectionBase
type ConfigurationSectionCollection = class
    inherit NameObjectCollectionBase
[<System.Serializable>]
type ConfigurationSectionCollection = class
    inherit NameObjectCollectionBase
Public NotInheritable Class ConfigurationSectionCollection
Inherits NameObjectCollectionBase
繼承
ConfigurationSectionCollection
屬性

範例

下列程式碼範例示範如何使用 ConfigurationSectionCollection 類別。

using System;
using System.Configuration;
using System.Collections;

namespace Samples.AspNet.Configuration
{

    // Define a custom section programmatically.
    public sealed class CustomSection :
        ConfigurationSection
    {
        // The collection (property bag) that contains 
        // the section properties.
        private static ConfigurationPropertyCollection _Properties;

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

        // The MasUsers 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;
            }
        }

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

                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;
            }
        }
    }

    class UsingCustomSectionCollection
    {

        // 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 the <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);
                }
            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine(err.ToString());
            }
        }

        static void GetAllKeys()
        {

            try
            {
                System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

                ConfigurationSectionCollection sections =
                    config.Sections;

                foreach (string key in sections.Keys)
                {
                    Console.WriteLine(
                     "Key value: {0}", key);
                }
            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine(err.ToString());
            }
        }


        static void Clear()
        {

            try
            {
                System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

                config.Sections.Clear();

                config.Save(ConfigurationSaveMode.Full);
            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine(err.ToString());
            }
        }


        static void GetSection()
        {

            try
            {
                CustomSection customSection =
                    ConfigurationManager.GetSection(
                    "CustomSection") as CustomSection;

                if (customSection == null)
                    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);
                }
            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine(err.ToString());
            }
        }

        static void GetEnumerator()
        {

            try
            {
                System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

                ConfigurationSectionCollection sections =
                    config.Sections;

                IEnumerator secEnum =
                    sections.GetEnumerator();

                int i = 0;
                while (secEnum.MoveNext())
                {
                    string setionName = sections.GetKey(i);
                    Console.WriteLine(
                        "Section name: {0}", setionName);
                    i += 1;
                }
            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine(err.ToString());
            }
        }

        static void GetKeys()
        {

            try
            {
                System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

                ConfigurationSectionCollection sections =
                    config.Sections;

                foreach (string key in sections.Keys)
                {

                    Console.WriteLine(
                     "Key value: {0}", key);
                }
            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine(err.ToString());
            }
        }


        static void GetItems()
        {

            try
            {
                System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

                ConfigurationSectionCollection sections =
                    config.Sections;

                ConfigurationSection section1 =
                    sections["runtime"];

                ConfigurationSection section2 =
                    sections[0];

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

                Console.WriteLine(
                    "Section2: {0}", section2.SectionInformation.Name);
            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine(err.ToString());
            }
        }


        static void Remove()
        {

            try
            {
                System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

                CustomSection customSection =
                    config.GetSection(
                    "CustomSection") as CustomSection;

                if (customSection != null)
                {
                    config.Sections.Remove("CustomSection");
                    customSection.SectionInformation.ForceSave = true;
                    config.Save(ConfigurationSaveMode.Full);
                }
                else
                    Console.WriteLine(
                        "CustomSection does not exists.");
            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine(err.ToString());
            }
        }

        static void AddSection()
        {

            try
            {
                System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

                CustomSection customSection =
                    new CustomSection();

                string index =
                    config.Sections.Count.ToString();

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

                string sectionName = "CustomSection" + index;

                TimeSpan ts = 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 (ConfigurationErrorsException err)
            {
                Console.WriteLine(err.ToString());
            }
        }

        // Exercise the collection.
        // Uncomment the function you want to exercise.
        // Start with CreateSection().
        static void Main(string[] args)
        {
            CreateSection();
            // AddSection();
            // GetSection();
            // GetEnumerator();
            // GetAllKeys();
            // GetKeys();
            // GetItems();

            // Remove();
            // Clear();
        }
    }
}
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


    ' 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




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


    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



    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


    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

    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


    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


    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


    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


    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



    ' 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

End Class

下列範例是上一個範例所使用的組態檔摘錄。

<?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>  

備註

ConfigurationSectionCollection使用類別逐一查看 物件的集合ConfigurationSection。 您可以使用 屬性或 Sections 屬性來存取這個物件的Sections集合。

類別 ConfigurationSectionCollection 也用於建立擴充類別的 ConfigurationSection 自定義類型。

屬性

Count

取得這個 ConfigurationSectionCollection 物件中的區段數目。

Count

取得 NameObjectCollectionBase 執行個體中包含的索引鍵/值組數目。

(繼承來源 NameObjectCollectionBase)
IsReadOnly

取得或設定值,表示 NameObjectCollectionBase 執行個體是否為唯讀。

(繼承來源 NameObjectCollectionBase)
Item[Int32]

取得指定的 ConfigurationSection 物件。

Item[String]

取得指定的 ConfigurationSection 物件。

Keys

取得這個 ConfigurationSection 物件中包含之所有 ConfigurationSectionCollection 物件的索引鍵。

Keys

取得 NameObjectCollectionBase.KeysCollection 執行個體,其中包含 NameObjectCollectionBase 執行個體內的所有索引鍵。

(繼承來源 NameObjectCollectionBase)

方法

Add(String, ConfigurationSection)

ConfigurationSection 物件新增至 ConfigurationSectionCollection 物件。

BaseAdd(String, Object)

將具有指定索引鍵和值的項目加入 NameObjectCollectionBase 執行個體。

(繼承來源 NameObjectCollectionBase)
BaseClear()

將所有項目從 NameObjectCollectionBase 執行個體中移除。

(繼承來源 NameObjectCollectionBase)
BaseGet(Int32)

取得 NameObjectCollectionBase 執行個體指定索引處之項目的值。

(繼承來源 NameObjectCollectionBase)
BaseGet(String)

NameObjectCollectionBase 執行個體取得具有指定索引鍵之第一個項目的值。

(繼承來源 NameObjectCollectionBase)
BaseGetAllKeys()

傳回 String 陣列,其中包含 NameObjectCollectionBase 執行個體中的所有索引鍵。

(繼承來源 NameObjectCollectionBase)
BaseGetAllValues()

傳回 Object 陣列,其中包含 NameObjectCollectionBase 執行個體中的所有值。

(繼承來源 NameObjectCollectionBase)
BaseGetAllValues(Type)

傳回指定類型的陣列,其中包含 NameObjectCollectionBase 執行個體中的所有值。

(繼承來源 NameObjectCollectionBase)
BaseGetKey(Int32)

取得 NameObjectCollectionBase 執行個體指定索引處之項目的索引鍵。

(繼承來源 NameObjectCollectionBase)
BaseHasKeys()

取得值,表示 NameObjectCollectionBase 執行個體是否包含其索引鍵不是 null 的項目。

(繼承來源 NameObjectCollectionBase)
BaseRemove(String)

將具有指定索引鍵的項目從 NameObjectCollectionBase 中移除。

(繼承來源 NameObjectCollectionBase)
BaseRemoveAt(Int32)

移除 NameObjectCollectionBase 執行個體指定索引處的項目。

(繼承來源 NameObjectCollectionBase)
BaseSet(Int32, Object)

設定 NameObjectCollectionBase 執行個體指定索引處之項目的值。

(繼承來源 NameObjectCollectionBase)
BaseSet(String, Object)

設定 NameObjectCollectionBase 執行個體中具有指定索引鍵之第一個項目的值 (如果有找到),否則將具有指定索引鍵和值的項目加入 NameObjectCollectionBase 執行個體。

(繼承來源 NameObjectCollectionBase)
Clear()

清除這個 ConfigurationSectionCollection 物件。

CopyTo(ConfigurationSection[], Int32)

複製這個 ConfigurationSectionCollection 物件至陣列。

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
Get(Int32)

取得這個 ConfigurationSection 物件中包含之指定的 ConfigurationSectionCollection 物件。

Get(String)

取得這個 ConfigurationSection 物件中包含之指定的 ConfigurationSectionCollection 物件。

GetEnumerator()

取得可以逐一查看這個 ConfigurationSectionCollection 物件的列舉值 (Enumerator)。

GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetKey(Int32)

取得包含在這個 ConfigurationSection 物件中指定之 ConfigurationSectionCollection 物件的索引鍵。

GetObjectData(SerializationInfo, StreamingContext)
已淘汰.

在序列化期間由系統使用。

GetObjectData(SerializationInfo, StreamingContext)
已淘汰.

實作 ISerializable 介面,並傳回序列化 NameObjectCollectionBase 執行個體所需的資料。

(繼承來源 NameObjectCollectionBase)
GetType()

取得目前執行個體的 Type

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
OnDeserialization(Object)

實作 ISerializable 介面,並於還原序列化完成時引發還原序列化事件。

(繼承來源 NameObjectCollectionBase)
Remove(String)

從這個 ConfigurationSection 物件中移除指定的 ConfigurationSectionCollection 物件。

RemoveAt(Int32)

從這個 ConfigurationSection 物件中移除指定的 ConfigurationSectionCollection 物件。

ToString()

傳回代表目前物件的字串。

(繼承來源 Object)

明確介面實作

ICollection.CopyTo(Array, Int32)

從目標陣列的指定索引開始,將整個 NameObjectCollectionBase 複製到相容的一維 Array

(繼承來源 NameObjectCollectionBase)
ICollection.IsSynchronized

取得值,表示是否要同步處理 (執行緒安全) 對 NameObjectCollectionBase 物件的存取。

(繼承來源 NameObjectCollectionBase)
ICollection.SyncRoot

取得可用來同步處理對 NameObjectCollectionBase 物件之存取的物件。

(繼承來源 NameObjectCollectionBase)

擴充方法

Cast<TResult>(IEnumerable)

IEnumerable 的項目轉換成指定的型別。

OfType<TResult>(IEnumerable)

根據指定的型別來篩選 IEnumerable 的項目。

AsParallel(IEnumerable)

啟用查詢的平行化作業。

AsQueryable(IEnumerable)

IEnumerable 轉換成 IQueryable

適用於

另請參閱