共用方式為


ConfigurationSectionGroupCollection 類別

定義

表示 ConfigurationSectionGroup 物件的集合。

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

範例

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

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

namespace Samples.Config
{

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

        public CustomSection()
        { }

        [ConfigurationProperty("fileName", DefaultValue = "default.txt",
            IsRequired = true, IsKey = false)]
        [StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;'\"|\\",
            MinLength = 1, MaxLength = 60)]
        public string FileName
        {
            get
            {
                return (string)this["fileName"];
            }
            set
            {
                this["fileName"] = value;
            }
        }
      
        [ConfigurationProperty("maxUsers", DefaultValue = (long)10000,
            IsRequired = false)]
        [LongValidator(MinValue = 1, MaxValue = 10000000,
            ExcludeRange = false)]
        public long MaxUsers
        {
            get
            {
                return (long)this["maxUsers"];
            }
            set
            {
                this["maxUsers"] = value;
            }
        }
       
        [ConfigurationProperty("maxIdleTime",
            DefaultValue = "0:10:0",
            IsRequired = false)]
        [TimeSpanValidator(MinValueString = "0:0:30",
            MaxValueString = "5:00:0",
            ExcludeRange = false)]
        public TimeSpan MaxIdleTime
        {
            get
            {
                return (TimeSpan)this["maxIdleTime"];
            }
            set
            {
                this["maxIdleTime"] = value;
            }
        }
    }

    // Define a custom section group.
    public sealed class CustomSectionGroup :
        ConfigurationSectionGroup
    {

        public CustomSectionGroup()
        {
        }

        public CustomSection Custom
        {
            get { return (CustomSection) 
                Sections.Get("CustomSection");}
        }
    }

    class UsingCustomSectionGroupCollection
    {

        // Create a custom section group.
        static void CreateSectionGroup()
        {
            try
            {

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

                // Create the section group entry  
                // in the <configSections> and the 
                // related target section in <configuration>.
                if (config.SectionGroups["CustomGroup"] == null)
                {
                    customSectionGroup = new CustomSectionGroup();
                    config.SectionGroups.Add("CustomGroup", 
                        customSectionGroup);
                    customSectionGroup.ForceDeclaration(true);
                    config.Save(ConfigurationSaveMode.Full);
                }
            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine(err.ToString());
            }
        }

        // Get the collection group keys i.e.,
        // the group names.
        //static void GetAllKeys()
        //{

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

        //        ConfigurationSectionGroupCollection groups =
        //            config.SectionGroups;
        //        groups.
        //        foreach (string name in groups.AllKeys)
        //        {
        //            Console.WriteLine(
        //             "Key value: {0}", name);
        //        }

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

        static void Clear()
        {

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

                config.SectionGroups.Clear();

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

        static void GetGroup()
        {

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

                ConfigurationSectionGroup customGroup =
                    config.SectionGroups.Get("CustomGroup");

                if (customGroup == null)
                    Console.WriteLine(
                        "Failed to load CustomSection.");
                else
                {
                    // Display section information
                    Console.WriteLine("Section group name:       {0}",
                        customGroup.SectionGroupName);
                    Console.WriteLine("Name:       {0}",
                        customGroup.Name);
                    Console.WriteLine("Type:   {0}",
                        customGroup.Type);
                }
            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine(err.ToString());
            }
        }

        static void GetEnumerator()
        {

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

                ConfigurationSectionGroupCollection groups =
                    config.SectionGroups;

                IEnumerator groupEnum =
                    groups.GetEnumerator();

                int i = 0;
                while (groupEnum.MoveNext())
                {
                    string groupName = groups.GetKey(i);
                    Console.WriteLine(
                        "Group name: {0}", groupName);
                    i += 1;
                }
            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine(err.ToString());
            }
        }

        // Get the collection keys i.e., the
        // group names.
        static void GetKeys()
        {

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

                ConfigurationSectionGroupCollection groups =
                    config.SectionGroups;

                foreach (string key in groups.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);

                ConfigurationSectionGroupCollection groups =
                    config.SectionGroups;

                ConfigurationSectionGroup group1 =
                    groups.Get("system.net");

                ConfigurationSectionGroup group2 =
                groups.Get("system.web");

                Console.WriteLine(
                     "Group1: {0}", group1.Name);

                Console.WriteLine(
                    "Group2: {0}", group2.Name);
            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine(err.ToString());
            }
        }


        static void Remove()
        {

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

                ConfigurationSectionGroup customGroup =
                    config.SectionGroups.Get("CustomGroup");

                if (customGroup != null)
                {
                    config.SectionGroups.Remove("CustomGroup");
                    config.Save(ConfigurationSaveMode.Full);
                }
                else
                    Console.WriteLine(
                        "CustomGroup does not exists.");
            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine(err.ToString());
            }
        }

        // Add custom section to the group.
        static void AddSection()
        {
            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>.
                ConfigurationSectionGroup customGroup;
                customGroup = config.SectionGroups.Get("CustomGroup");

                if (customGroup.Sections.Get("CustomSection") == null)
                {
                    customSection = new CustomSection();
                    customGroup.Sections.Add("CustomSection",
                        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 CreateSectionGroup().
        static void Main(string[] args)
        {
            CreateSectionGroup();
            AddSection();
            // GetAllKeys();
            // GetGroup();
            
            // GetEnumerator();
            
            // GetKeys();
            
            // GetItems();

            // Remove();
            // Clear();
        }
    }
}
Imports System.Configuration
Imports System.Collections


' Define a custom section.
NotInheritable Public Class CustomSection
   Inherits ConfigurationSection
   
   
   Public Sub New()
   End Sub
   
    <ConfigurationProperty("fileName", _
    DefaultValue:="default.txt", _
    IsRequired:=True, _
    IsKey:=False), _
    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("maxUsers", _
    DefaultValue:=10000, _
    IsRequired:=False), _
    LongValidator(MinValue:=1, _
    MaxValue:=10000000, _
    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

    <ConfigurationProperty("maxIdleTime", _
    DefaultValue:="0:10:0", _
    IsRequired:=False), _
    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

' Define a custom section group.

NotInheritable Public Class CustomSectionGroup
   Inherits ConfigurationSectionGroup
   
   
   Public Sub New()
   End Sub

   
   Public ReadOnly Property Custom() As CustomSection
      Get
            Return CType(Sections.Get("CustomSection"), _
            CustomSection)
      End Get
    End Property

End Class


Class UsingCustomSectionGroupCollection

   
   ' Create a custom section group.
   Shared Sub CreateSectionGroup()
      Try
         
         Dim customSectionGroup As CustomSectionGroup
         
         ' Get the current configuration file.
            Dim config As System.Configuration.Configuration = _
            ConfigurationManager.OpenExeConfiguration( _
            ConfigurationUserLevel.None)
         
         ' Create the section group entry  
         ' in the <configSections> and the 
         ' related target section in <configuration>.
         If config.SectionGroups("CustomGroup") Is Nothing Then
            customSectionGroup = New CustomSectionGroup()
            config.SectionGroups.Add("CustomGroup", customSectionGroup)
            customSectionGroup.ForceDeclaration(True)
            config.Save(ConfigurationSaveMode.Full)
         End If
      
      Catch err As ConfigurationErrorsException
         Console.WriteLine(err.ToString())
      End Try
   End Sub
    
   
   ' Get the collection group keys i.e.,
   ' the group names.
    'Shared Sub GetAllKeys()

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

    '         Dim groups _
    '         As ConfigurationSectionGroupCollection = _
    '         config.SectionGroups

    '      Dim name As String
    '      For Each name In  groups.AllKeys
    '         Console.WriteLine("Key value: {0}", name)
    '      Next name


    '   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.SectionGroups.Clear()
         
         config.Save(ConfigurationSaveMode.Full)
      Catch err As ConfigurationErrorsException
         Console.WriteLine(err.ToString())
      End Try
   End Sub
   

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

            Dim groups _
            As ConfigurationSectionGroupCollection = _
            config.SectionGroups

            Dim customGroup _
            As ConfigurationSectionGroup = _
            groups.Get("CustomGroup")
         
         
         If customGroup Is Nothing Then
                Console.WriteLine( _
                "Failed to load CustomGroup.")
         Else
            ' Display section information
                Console.WriteLine("Name:       {0}", _
                customGroup.Name)
                Console.WriteLine("Type:   {0}", _
                customGroup.Type)
         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 groups _
            As ConfigurationSectionGroupCollection = _
            config.SectionGroups

            Dim groupEnum As IEnumerator = _
            groups.GetEnumerator()
         
         Dim i As Integer = 0
         While groupEnum.MoveNext()
            Dim groupName As String = groups.GetKey(i)
            Console.WriteLine("Group name: {0}", groupName)
            i += 1
         End While

      Catch err As ConfigurationErrorsException
         Console.WriteLine(err.ToString())
      End Try
   End Sub
   
   
   ' Get the collection keys i.e., the
   ' group names.
   Shared Sub GetKeys()
      
      Try
            Dim config _
          As System.Configuration.Configuration = _
          ConfigurationManager.OpenExeConfiguration( _
          ConfigurationUserLevel.None)

            Dim groups _
            As ConfigurationSectionGroupCollection = _
            config.SectionGroups

         Dim key As String
         For Each key In  groups.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 groups _
            As ConfigurationSectionGroupCollection = _
            config.SectionGroups

            Dim group1 As ConfigurationSectionGroup = _
            groups.Get("system.net")
         
            Dim group2 As ConfigurationSectionGroup = _
            groups.Get("system.web")
         
         
         Console.WriteLine("Group1: {0}", group1.Name)
         
         Console.WriteLine("Group2: {0}", group2.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 groups _
            As ConfigurationSectionGroupCollection = _
            config.SectionGroups

            Dim customGroup _
            As ConfigurationSectionGroup = groups.Get("CustomGroup")
         
         If Not (customGroup Is Nothing) Then
            config.SectionGroups.Remove("CustomGroup")
            config.Save(ConfigurationSaveMode.Full)
         Else
                Console.WriteLine( _
                "CustomGroup does not exists.")
         End If
      
      Catch err As ConfigurationErrorsException
         Console.WriteLine(err.ToString())
      End Try
   End Sub
   
   
   
   ' Add custom section to the group.
   Shared Sub AddSection()
      Try
         
         Dim customSection As CustomSection
         
         ' Get the current configuration file.
            Dim config _
     As System.Configuration.Configuration = _
     ConfigurationManager.OpenExeConfiguration( _
     ConfigurationUserLevel.None)

            Dim groups _
            As ConfigurationSectionGroupCollection = _
            config.SectionGroups

         ' Create the section entry  
         ' in the <configSections> and the 
         ' related target section in <configuration>.
         Dim customGroup As ConfigurationSectionGroup
            customGroup = groups.Get("CustomGroup")
         
            If customGroup.Sections.Get( _
            "CustomSection") Is Nothing Then
                customSection = New CustomSection()
                customGroup.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
   
   
   ' Exercise the collection.
   ' Uncomment the function you want to exercise.
    ' Start with CreateSectionGroup().
    Public Overloads Shared Sub Main(ByVal args() As String)
        CreateSectionGroup()
        AddSection()
        ' GetEnumerator();
        ' GetKeys();
        ' GetItems();
        ' Remove();
        ' Clear();

    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>  

備註

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

類別 ConfigurationSectionGroupCollection 也用於建立擴充類別的 ConfigurationSectionGroup 自定義類型。

屬性

Count

取得集合中區段群組的數目。

Count

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

(繼承來源 NameObjectCollectionBase)
IsReadOnly

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

(繼承來源 NameObjectCollectionBase)
Item[Int32]

取得集合中位於指定之索引處的 ConfigurationSectionGroup 物件。

Item[String]

取得集合中指定之名稱的 ConfigurationSectionGroup 物件。

Keys

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

Keys

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

(繼承來源 NameObjectCollectionBase)

方法

Add(String, ConfigurationSectionGroup)

ConfigurationSectionGroup 物件加入至這個 ConfigurationSectionGroupCollection 物件。

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()

清除集合。

CopyTo(ConfigurationSectionGroup[], Int32)

複製這個 ConfigurationSectionGroupCollection 物件至陣列。

Equals(Object)

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

(繼承來源 Object)
Get(Int32)

取得集合中包含的指定之 ConfigurationSectionGroup 物件。

Get(String)

從集合取得指定的 ConfigurationSectionGroup 物件。

GetEnumerator()

取得可逐一查看 ConfigurationSectionGroupCollection 物件的列舉值。

GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetKey(Int32)

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

GetObjectData(SerializationInfo, StreamingContext)
已淘汰.

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

GetObjectData(SerializationInfo, StreamingContext)
已淘汰.

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

(繼承來源 NameObjectCollectionBase)
GetType()

取得目前執行個體的 Type

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
OnDeserialization(Object)

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

(繼承來源 NameObjectCollectionBase)
Remove(String)

從這個 ConfigurationSectionGroup 物件中移除具有指定之名稱的 ConfigurationSectionGroupCollection 物件。

RemoveAt(Int32)

從這個 ConfigurationSectionGroup 物件中移除具有指定之索引的 ConfigurationSectionGroupCollection 物件。

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

適用於

另請參閱