Export (0) Print
Expand All

ConfigurationSectionGroupCollection Class

Represents a collection of ConfigurationSectionGroup objects.

System.Object
  System.Collections.Specialized.NameObjectCollectionBase
    System.Configuration.ConfigurationSectionGroupCollection

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

[SerializableAttribute]
public sealed class ConfigurationSectionGroupCollection : NameObjectCollectionBase

The ConfigurationSectionGroupCollection type exposes the following members.

  NameDescription
Public propertyCountGets the number of section groups in the collection. (Overrides NameObjectCollectionBase.Count.)
Public propertyItem[Int32]Gets the ConfigurationSectionGroup object whose index is specified from the collection.
Public propertyItem[String]Gets the ConfigurationSectionGroup object whose name is specified from the collection.
Public propertyKeysGets the keys to all ConfigurationSectionGroup objects contained in this ConfigurationSectionGroupCollection object. (Overrides NameObjectCollectionBase.Keys.)
Top

  NameDescription
Public methodAddAdds a ConfigurationSectionGroup object to this ConfigurationSectionGroupCollection object.
Public methodClearClears the collection.
Public methodCopyToCopies this ConfigurationSectionGroupCollection object to an array.
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Public methodGet(Int32)Gets the specified ConfigurationSectionGroup object contained in the collection.
Public methodGet(String)Gets the specified ConfigurationSectionGroup object from the collection.
Public methodGetEnumeratorGets an enumerator that can iterate through the ConfigurationSectionGroupCollection object. (Overrides NameObjectCollectionBase.GetEnumerator().)
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetKeyGets the key of the specified ConfigurationSectionGroup object contained in this ConfigurationSectionGroupCollection object.
Public methodGetObjectDataUsed by the system during serialization. (Overrides NameObjectCollectionBase.GetObjectData(SerializationInfo, StreamingContext).)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodOnDeserializationImplements the ISerializable interface and raises the deserialization event when the deserialization is complete. (Inherited from NameObjectCollectionBase.)
Public methodRemoveRemoves the ConfigurationSectionGroup object whose name is specified from this ConfigurationSectionGroupCollection object.
Public methodRemoveAtRemoves the ConfigurationSectionGroup object whose index is specified from this ConfigurationSectionGroupCollection object.
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

  NameDescription
Explicit interface implemetationPrivate methodICollection.CopyToCopies the entire NameObjectCollectionBase to a compatible one-dimensional Array, starting at the specified index of the target array. (Inherited from NameObjectCollectionBase.)
Explicit interface implemetationPrivate propertyICollection.IsSynchronizedGets a value indicating whether access to the NameObjectCollectionBase object is synchronized (thread safe). (Inherited from NameObjectCollectionBase.)
Explicit interface implemetationPrivate propertyICollection.SyncRootGets an object that can be used to synchronize access to the NameObjectCollectionBase object. (Inherited from NameObjectCollectionBase.)
Top

Use the ConfigurationSectionGroupCollection class to iterate through a collection of ConfigurationSectionGroup objects. You can access this collection of objects using the SectionGroups property or the SectionGroups property.

The ConfigurationSectionGroupCollection class is also used in the creation of custom types that extend the ConfigurationSectionGroup class.

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

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


    }
}

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>

.NET Framework

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

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, 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.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2014 Microsoft