Leer en inglés

Compartir a través de


ConfigurationSectionCollection Clase

Definición

Representa una colección de secciones relacionadas en un archivo de configuración.

public sealed class ConfigurationSectionCollection : System.Collections.Specialized.NameObjectCollectionBase
[System.Serializable]
public sealed class ConfigurationSectionCollection : System.Collections.Specialized.NameObjectCollectionBase
Herencia
ConfigurationSectionCollection
Atributos

Ejemplos

En el ejemplo de código siguiente se muestra cómo se utiliza la clase 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();
        }
    }
}

El ejemplo siguiente es un extracto del archivo de configuración utilizado por el ejemplo anterior.

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

Comentarios

Use la ConfigurationSectionCollection clase para recorrer en iteración una colección de ConfigurationSection objetos . Puede acceder a esta colección de objetos mediante la Sections propiedad o la Sections propiedad .

La ConfigurationSectionCollection clase también se usa en la creación de tipos personalizados que extienden la ConfigurationSection clase .

Propiedades

Count

Obtiene el número de secciones que hay en este objeto ConfigurationSectionCollection.

Count

Obtiene el número de pares de clave y valor incluidos en la instancia NameObjectCollectionBase.

(Heredado de NameObjectCollectionBase)
IsReadOnly

Obtiene o establece un valor que indica si la instancia NameObjectCollectionBase es de solo lectura.

(Heredado de NameObjectCollectionBase)
Item[Int32]

Obtiene el objeto ConfigurationSection especificado.

Item[String]

Obtiene el objeto ConfigurationSection especificado.

Keys

Obtiene las claves de todos los objetos ConfigurationSection incluidos en este objeto ConfigurationSectionCollection.

Keys

Obtiene una instancia NameObjectCollectionBase.KeysCollection que contiene todas las claves de la instancia NameObjectCollectionBase.

(Heredado de NameObjectCollectionBase)

Métodos

Add(String, ConfigurationSection)

Agrega un objeto ConfigurationSection al objeto ConfigurationSectionCollection.

BaseAdd(String, Object)

Agrega una entrada con la clave y el valor especificados a la instancia NameObjectCollectionBase.

(Heredado de NameObjectCollectionBase)
BaseClear()

Elimina todas las entradas de la instancia NameObjectCollectionBase.

(Heredado de NameObjectCollectionBase)
BaseGet(Int32)

Obtiene el valor de la entrada que se encuentra en el índice especificado de la instancia NameObjectCollectionBase.

(Heredado de NameObjectCollectionBase)
BaseGet(String)

Obtiene el valor de la primera entrada con la clave especificada desde la instancia NameObjectCollectionBase.

(Heredado de NameObjectCollectionBase)
BaseGetAllKeys()

Devuelve una matriz String que contiene todas las claves de la instancia NameObjectCollectionBase.

(Heredado de NameObjectCollectionBase)
BaseGetAllValues()

Devuelve una matriz Object que contiene todos los valores de la instancia NameObjectCollectionBase.

(Heredado de NameObjectCollectionBase)
BaseGetAllValues(Type)

Devuelve una matriz del tipo especificado que contiene todos los valores de la instancia NameObjectCollectionBase.

(Heredado de NameObjectCollectionBase)
BaseGetKey(Int32)

Obtiene la clave de la entrada que se encuentra en el índice especificado de la instancia NameObjectCollectionBase.

(Heredado de NameObjectCollectionBase)
BaseHasKeys()

Obtiene un valor que indica si la instancia NameObjectCollectionBase contiene entradas cuyas claves no son null.

(Heredado de NameObjectCollectionBase)
BaseRemove(String)

Quita las entradas con la clave especificada de la instancia de NameObjectCollectionBase.

(Heredado de NameObjectCollectionBase)
BaseRemoveAt(Int32)

Elimina la entrada que se encuentra en el índice especificado de la instancia NameObjectCollectionBase.

(Heredado de NameObjectCollectionBase)
BaseSet(Int32, Object)

Establece el valor de la entrada que se encuentra en el índice especificado de la instancia NameObjectCollectionBase.

(Heredado de NameObjectCollectionBase)
BaseSet(String, Object)

Establece el valor de la primera entrada con la clave especificada de la instancia NameObjectCollectionBase, si la encuentra; en caso contrario, agrega una entrada con la clave y el valor especificados a la instancia NameObjectCollectionBase.

(Heredado de NameObjectCollectionBase)
Clear()

Borra este objeto ConfigurationSectionCollection.

CopyTo(ConfigurationSection[], Int32)

Copia esta colección ConfigurationSectionCollection en una matriz.

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
Get(Int32)

Obtiene el objeto ConfigurationSection especificado que incluye este objeto ConfigurationSectionCollection.

Get(String)

Obtiene el objeto ConfigurationSection especificado que incluye este objeto ConfigurationSectionCollection.

GetEnumerator()

Obtiene un enumerador que recorre en iteración este objeto ConfigurationSectionCollection.

GetHashCode()

Sirve como la función hash predeterminada.

(Heredado de Object)
GetKey(Int32)

Obtiene la clave del objeto ConfigurationSection especificado incluido en este objeto ConfigurationSectionCollection.

GetObjectData(SerializationInfo, StreamingContext)
Obsoletos.

Método que utiliza el sistema durante la serialización.

GetObjectData(SerializationInfo, StreamingContext)
Obsoletos.

Implementa la interfaz de ISerializable y devuelve los datos necesarios para serializar la instancia de NameObjectCollectionBase.

(Heredado de NameObjectCollectionBase)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
OnDeserialization(Object)

Implementa la interfaz ISerializable y genera el evento de deserialización cuando esta ha finalizado.

(Heredado de NameObjectCollectionBase)
Remove(String)

Quita el objeto ConfigurationSection especificado de este objeto ConfigurationSectionCollection.

RemoveAt(Int32)

Quita el objeto ConfigurationSection especificado de este objeto ConfigurationSectionCollection.

ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Implementaciones de interfaz explícitas

ICollection.CopyTo(Array, Int32)

Copia la totalidad de NameObjectCollectionBase en una matriz Array unidimensional compatible, comenzando en el índice especificado de la matriz de destino.

(Heredado de NameObjectCollectionBase)
ICollection.IsSynchronized

Obtiene un valor que indica si el acceso al objeto NameObjectCollectionBase está sincronizado (es seguro para subprocesos).

(Heredado de NameObjectCollectionBase)
ICollection.SyncRoot

Obtiene un objeto que puede utilizarse para sincronizar el acceso al objeto NameObjectCollectionBase.

(Heredado de NameObjectCollectionBase)

Métodos de extensión

Cast<TResult>(IEnumerable)

Convierte los elementos de IEnumerable en el tipo especificado.

OfType<TResult>(IEnumerable)

Filtra los elementos de IEnumerable en función de un tipo especificado.

AsParallel(IEnumerable)

Habilita la paralelización de una consulta.

AsQueryable(IEnumerable)

Convierte una interfaz IEnumerable en IQueryable.

Se aplica a

Producto Versiones
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9

Consulte también