Leer en inglés

Compartir a través de


ConfigurationElementCollection Clase

Definición

Representa un elemento de configuración que contiene una colección de elementos secundarios.

C#
public abstract class ConfigurationElementCollection : System.Configuration.ConfigurationElement, System.Collections.ICollection
Herencia
ConfigurationElementCollection
Derivado
Implementaciones

Ejemplos

En el ejemplo siguiente se muestra cómo usar .ConfigurationElementCollection

El primer ejemplo consta de tres clases: UrlsSection, UrlsCollection y UrlConfigElement. La UrlsSection clase usa ConfigurationCollectionAttribute para definir una sección de configuración personalizada. Esta sección contiene una colección de direcciones URL (definida por la UrlsCollection clase ) de elementos url (definidos por la UrlConfigElement clase ).

C#
using System;
using System.Configuration;

// Define a UrlsSection custom section that contains a 
// UrlsCollection collection of UrlConfigElement elements.
public class UrlsSection : ConfigurationSection
{

    // Declare the UrlsCollection collection property.
    [ConfigurationProperty("urls", IsDefaultCollection = false)]
    [ConfigurationCollection(typeof(UrlsCollection),
        AddItemName = "add",
        ClearItemsName = "clear",
        RemoveItemName = "remove")]
    public UrlsCollection Urls
    {
        get
        {
            UrlsCollection urlsCollection =
                (UrlsCollection)base["urls"];

            return urlsCollection;
        }

        set
        {
            UrlsCollection urlsCollection = value;
        }
    }

    // Create a new instance of the UrlsSection.
    // This constructor creates a configuration element 
    // using the UrlConfigElement default values.
    // It assigns this element to the collection.
    public UrlsSection()
    {
        UrlConfigElement url = new UrlConfigElement();
        Urls.Add(url);
    }
}

// Define the UrlsCollection that contains the 
// UrlsConfigElement elements.
// This class shows how to use the ConfigurationElementCollection.
public class UrlsCollection : ConfigurationElementCollection
{

    public UrlsCollection()
    {
    }

    public override ConfigurationElementCollectionType CollectionType
    {
        get
        {
            return ConfigurationElementCollectionType.AddRemoveClearMap;
        }
    }

    protected override ConfigurationElement CreateNewElement()
    {
        return new UrlConfigElement();
    }

    protected override Object GetElementKey(ConfigurationElement element)
    {
        return ((UrlConfigElement)element).Name;
    }

    public UrlConfigElement this[int index]
    {
        get
        {
            return (UrlConfigElement)BaseGet(index);
        }
        set
        {
            if (BaseGet(index) != null)
            {
                BaseRemoveAt(index);
            }
            BaseAdd(index, value);
        }
    }

    new public UrlConfigElement this[string Name]
    {
        get
        {
            return (UrlConfigElement)BaseGet(Name);
        }
    }

    public int IndexOf(UrlConfigElement url)
    {
        return BaseIndexOf(url);
    }

    public void Add(UrlConfigElement url)
    {
        BaseAdd(url);

        // Your custom code goes here.
    }

    protected override void BaseAdd(ConfigurationElement element)
    {
        BaseAdd(element, false);

        // Your custom code goes here.
    }
    
    public void Remove(UrlConfigElement url)
    {
        if (BaseIndexOf(url) >= 0)
        {
            BaseRemove(url.Name);
            // Your custom code goes here.
            Console.WriteLine("UrlsCollection: {0}", "Removed collection element!");
        }
    }
    
    public void RemoveAt(int index)
    {
        BaseRemoveAt(index);

        // Your custom code goes here.
    }
    
    public void Remove(string name)
    {
        BaseRemove(name);

        // Your custom code goes here.
    }
    
    public void Clear()
    {
        BaseClear();

        // Your custom code goes here.
        Console.WriteLine("UrlsCollection: {0}", "Removed entire collection!");
    }
}

// Define the UrlsConfigElement elements that are contained 
// by the UrlsCollection.
public class UrlConfigElement : ConfigurationElement
{
    public UrlConfigElement(String name, String url, int port)
    {
        this.Name = name;
        this.Url = url;
        this.Port = port;
    }

    public UrlConfigElement()
    {
    }

    [ConfigurationProperty("name", DefaultValue = "Contoso",
        IsRequired = true, IsKey = true)]
    public string Name
    {
        get
        {
            return (string)this["name"];
        }
        set
        {
            this["name"] = value;
        }
    }

    [ConfigurationProperty("url", DefaultValue = "http://www.contoso.com",
        IsRequired = true)]
    [RegexStringValidator(@"\w+:\/\/[\w.]+\S*")]
    public string Url
    {
        get
        {
            return (string)this["url"];
        }
        set
        {
            this["url"] = value;
        }
    }
    
    [ConfigurationProperty("port", DefaultValue = (int)4040, IsRequired = false)]
    [IntegerValidator(MinValue = 0, MaxValue = 8080, ExcludeRange = false)]
    public int Port
    {
        get
        {
            return (int)this["port"];
        }
        set
        {
            this["port"] = value;
        }
    }
}

En este segundo ejemplo de código se usan las clases especificadas antes. Estos dos ejemplos se combinan en un proyecto de aplicación de consola.

C#
using System;
using System.Configuration;
using System.Text;

class UsingConfigurationCollectionElement
{

    // Create a custom section and save it in the 
    // application configuration file.
    static void CreateCustomSection()
    {
        try
        {

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

            // Add the custom section to the application
            // configuration file.
            UrlsSection myUrlsSection = (UrlsSection)config.Sections["MyUrls"];

            if (myUrlsSection == null)
            {
                //  The configuration file does not contain the
                // custom section yet. Create it.
                myUrlsSection = new UrlsSection();

                config.Sections.Add("MyUrls", myUrlsSection);

                // Save the application configuration file.
                myUrlsSection.SectionInformation.ForceSave = true;
                config.Save(ConfigurationSaveMode.Modified); 
            }
            else
                if (myUrlsSection.Urls.Count == 0)
                {

                    // The configuration file contains the
                    // custom section but its element collection is empty.
                    // Initialize the collection. 
                    UrlConfigElement url = new UrlConfigElement();
                    myUrlsSection.Urls.Add(url);

                    // Save the application configuration file.
                    myUrlsSection.SectionInformation.ForceSave = true;
                    config.Save(ConfigurationSaveMode.Modified);
                }

            Console.WriteLine("Created custom section in the application configuration file: {0}",
                config.FilePath);
            Console.WriteLine();
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("CreateCustomSection: {0}", err.ToString());
        }
    }

    static void ReadCustomSection()
    {
        try
        {
            // Get the application configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            // Read and display the custom section.
            UrlsSection myUrlsSection =
               config.GetSection("MyUrls") as UrlsSection;

            if (myUrlsSection == null)
            {
                Console.WriteLine("Failed to load UrlsSection.");
            }
            else
            {
                Console.WriteLine("Collection elements contained in the custom section collection:");
                for (int i = 0; i < myUrlsSection.Urls.Count; i++)
                {
                    Console.WriteLine("   Name={0} URL={1} Port={2}",
                        myUrlsSection.Urls[i].Name,
                        myUrlsSection.Urls[i].Url,
                        myUrlsSection.Urls[i].Port);
                }
            }
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("ReadCustomSection(string): {0}", err.ToString());
        }
    }

    // Add an element to the custom section collection.
    // This function uses the ConfigurationCollectionElement Add method.
    static void AddCollectionElement()
    {
        try
        {

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

            // Get the custom configuration section.
            UrlsSection myUrlsSection = config.GetSection("MyUrls") as UrlsSection;

            // Add the element to the collection in the custom section.
            if (config.Sections["MyUrls"] != null)
            {
                UrlConfigElement urlElement = new UrlConfigElement();
                urlElement.Name = "Microsoft";
                urlElement.Url = "http://www.microsoft.com";
                urlElement.Port = 8080;
                
                // Use the ConfigurationCollectionElement Add method
                // to add the new element to the collection.
                myUrlsSection.Urls.Add(urlElement);

                // Save the application configuration file.
                myUrlsSection.SectionInformation.ForceSave = true;
                config.Save(ConfigurationSaveMode.Modified);

                Console.WriteLine("Added collection element to the custom section in the configuration file: {0}",
                    config.FilePath);
                Console.WriteLine();
            }
            else
            {
                Console.WriteLine("You must create the custom section first.");
            }
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("AddCollectionElement: {0}", err.ToString());
        }
    }

    // Remove element from the custom section collection.
    // This function uses one of the ConfigurationCollectionElement 
    // overloaded Remove methods.
    static void RemoveCollectionElement()
    {
        try
        {

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

            // Get the custom configuration section.
            UrlsSection myUrlsSection = config.GetSection("MyUrls") as UrlsSection;

            // Remove the element from the custom section.
            if (config.Sections["MyUrls"] != null)
            {
                UrlConfigElement urlElement = new UrlConfigElement();
                urlElement.Name = "Microsoft";
                urlElement.Url = "http://www.microsoft.com";
                urlElement.Port = 8080;

                // Use one of the ConfigurationCollectionElement Remove 
                // overloaded methods to remove the element from the collection.
                myUrlsSection.Urls.Remove(urlElement);

                // Save the application configuration file.
                myUrlsSection.SectionInformation.ForceSave = true;
                config.Save(ConfigurationSaveMode.Full);

                Console.WriteLine("Removed collection element from he custom section in the configuration file: {0}",
                    config.FilePath);
                Console.WriteLine();
            }
            else
            {
                Console.WriteLine("You must create the custom section first.");
            }
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("RemoveCollectionElement: {0}", err.ToString());
        }
    }

    // Remove the collection of elements from the custom section.
    // This function uses the ConfigurationCollectionElement Clear method.
    static void ClearCollectionElements()
    {
        try
        {

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

            // Get the custom configuration section.
            UrlsSection myUrlsSection = config.GetSection("MyUrls") as UrlsSection;

            // Remove the collection of elements from the section.
            if (config.Sections["MyUrls"] != null)
            {
                myUrlsSection.Urls.Clear();

                // Save the application configuration file.
                myUrlsSection.SectionInformation.ForceSave = true;
                config.Save(ConfigurationSaveMode.Full);

                Console.WriteLine("Removed collection of elements from he custom section in the configuration file: {0}",
                    config.FilePath);
                Console.WriteLine();
            }
            else
            {
                Console.WriteLine("You must create the custom section first.");
            }
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("ClearCollectionElements: {0}", err.ToString());
        }
    }

    public static void UserMenu()
    {
        string applicationName =
           Environment.GetCommandLineArgs()[0] + ".exe";
        StringBuilder buffer = new StringBuilder();

        buffer.AppendLine("Application: " + applicationName);
        buffer.AppendLine("Make your selection.");
        buffer.AppendLine("?    -- Display help.");
        buffer.AppendLine("Q,q  -- Exit the application.");
        buffer.Append("1    -- Create a custom section that");
        buffer.AppendLine(" contains a collection of elements.");
        buffer.Append("2    -- Read the custom section that");
        buffer.AppendLine(" contains a collection of custom elements.");
        buffer.Append("3    -- Add a collection element to");
        buffer.AppendLine(" the custom section.");
        buffer.Append("4    -- Remove a collection element from");
        buffer.AppendLine(" the custom section.");
        buffer.Append("5    -- Clear the collection of elements from");
        buffer.AppendLine(" the custom section.");
        
        Console.Write(buffer.ToString());
    }

    // Obtain user's input and provide
    // feedback.
    static void Main(string[] args)
    {
        // Define user selection string.
        string selection;

        // Get the name of the application.
        string appName =
          Environment.GetCommandLineArgs()[0];

        // Get user selection.
        while (true)
        {

            UserMenu();
            Console.Write("> ");
            selection = Console.ReadLine();
            if (!string.IsNullOrEmpty(selection))
                break;
        }

        while (selection.ToLower() != "q")
        {
            // Process user's input.
            switch (selection)
            {
                case "1":
                    // Create a custom section and save it in the 
                    // application configuration file.
                    CreateCustomSection();
                    break;

                case "2":
                    // Read the custom section from the
                    // application configuration file.
                    ReadCustomSection();
                    break;

                case "3":
                    // Add a collection element to the
                    // custom section.
                    AddCollectionElement();
                    break;

                case "4":
                    // Remove a collection element from the
                    // custom section.
                    RemoveCollectionElement();
                    break;

                case "5":
                    // Clear the collection of elements from the
                    // custom section.
                    ClearCollectionElements();
                    break;

                default:
                    UserMenu();
                    break;
            }
            Console.Write("> ");
            selection = Console.ReadLine();
        }
    }
}

Al ejecutar la aplicación de consola, se crea una instancia de la UrlsSection clase y se generan los siguientes elementos de configuración en el archivo de configuración de la aplicación:

XML
<configuration>  
    <configSections>  
        <section name="MyUrls" type="UrlsSection,   
          ConfigurationElementCollection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />  
    </configSections>  
    <MyUrls>  
        <urls>  
           <add name="Contoso" url="http://www.contoso.com" port="4040" />  
        </urls>  
    </MyUrls>  
</configuration  

Comentarios

ConfigurationElementCollection representa una colección de elementos dentro de un archivo de configuración.

Nota

Un elemento de un archivo de configuración hace referencia a un elemento XML básico o a una sección. Un elemento simple es una etiqueta XML con atributos relacionados, si existe. Un elemento simple constituye una sección. Las secciones complejas pueden contener uno o varios elementos simples, una colección de elementos y otras secciones.

Se usa ConfigurationElementCollection para trabajar con una colección de ConfigurationElement objetos . Implemente esta clase para agregar colecciones de elementos personalizados ConfigurationElement a .ConfigurationSection

Notas a los implementadores

Puede usar un modelo de codificación mediante programación o declarativo (con atributos) para crear un elemento de configuración personalizado.

El modelo de programación requiere que para cada atributo de elemento cree una propiedad para obtener y establecer su valor, y que se agregue al contenedor de propiedades interno de la clase base subyacente ConfigurationElement .

El modelo declarativo, también denominado modelo con atributos, permite definir un atributo de elemento mediante una propiedad y configurarlo con atributos. Estos atributos indican al sistema de configuración ASP.NET sobre los tipos de propiedad y sus valores predeterminados. ASP.NET puede usar la reflexión para obtener esta información y, a continuación, crear los objetos de propiedad de elemento y realizar la inicialización necesaria.

Constructores

Propiedades

AddElementName

Obtiene o establece el nombre del objeto ConfigurationElement que se va a asociar a la operación de adición en la colección ConfigurationElementCollection cuando se reemplaza en una clase derivada.

ClearElementName

Obtiene o establece el nombre del objeto ConfigurationElement que se va a asociar a la operación de borrado en la colección ConfigurationElementCollection cuando se reemplaza en una clase derivada.

CollectionType

Obtiene el tipo de ConfigurationElementCollection.

Count

Obtiene el número de elementos de la colección.

CurrentConfiguration

Obtiene una referencia a la instancia de Configuration de nivel superior que representa la jerarquía de configuración a la que pertenece la instancia actual de ConfigurationElement.

(Heredado de ConfigurationElement)
ElementInformation

Obtiene un objeto ElementInformation que contiene la funcionalidad e información no personalizable del objeto ConfigurationElement.

(Heredado de ConfigurationElement)
ElementName

Obtiene el nombre que se utiliza para identificar esta colección de elementos en el archivo de configuración cuando se reemplaza en una clase derivada.

ElementProperty

Obtiene el objeto ConfigurationElementProperty que representa al propio objeto ConfigurationElement.

(Heredado de ConfigurationElement)
EmitClear

Obtiene o establece un valor que especifica si se ha borrado la colección.

EvaluationContext

Obtiene el objeto ContextInformation para el objeto ConfigurationElement.

(Heredado de ConfigurationElement)
HasContext

Obtiene un valor que indica si la propiedad CurrentConfiguration es null.

(Heredado de ConfigurationElement)
IsSynchronized

Obtiene un valor que indica si se sincroniza el acceso a la recopilación.

Item[ConfigurationProperty]

Obtiene o establece una propiedad o atributo de este elemento de configuración.

(Heredado de ConfigurationElement)
Item[String]

Obtiene o establece una propiedad, un atributo o un elemento secundario de este elemento de configuración.

(Heredado de ConfigurationElement)
LockAllAttributesExcept

Obtiene la colección de atributos bloqueados.

(Heredado de ConfigurationElement)
LockAllElementsExcept

Obtiene la colección de elementos bloqueados.

(Heredado de ConfigurationElement)
LockAttributes

Obtiene la colección de atributos bloqueados.

(Heredado de ConfigurationElement)
LockElements

Obtiene la colección de elementos bloqueados.

(Heredado de ConfigurationElement)
LockItem

Obtiene o establece un valor que indica si el elemento está bloqueado.

(Heredado de ConfigurationElement)
Properties

Obtiene la colección de propiedades.

(Heredado de ConfigurationElement)
RemoveElementName

Obtiene o establece el nombre del objeto ConfigurationElement que se va a asociar a la operación de eliminación en la colección ConfigurationElementCollection cuando se reemplaza en una clase derivada.

SyncRoot

Obtiene un objeto que se utiliza para sincronizar el acceso a la colección ConfigurationElementCollection.

ThrowOnDuplicate

Obtiene un valor que indica si el intento de agregar un objeto ConfigurationElement duplicado a la colección ConfigurationElementCollection va a hacer que se produzca una excepción.

Métodos

BaseAdd(ConfigurationElement)

Agrega un elemento de configuración a la colección ConfigurationElementCollection.

BaseAdd(ConfigurationElement, Boolean)

Agrega un elemento de configuración a la colección de elementos de configuración.

BaseAdd(Int32, ConfigurationElement)

Agrega un elemento de configuración a la colección de elementos de configuración.

BaseClear()

Quita todos los objetos de elemento de configuración de la colección.

BaseGet(Int32)

Obtiene el elemento de configuración en la ubicación de índice especificada.

BaseGet(Object)

Devuelve el elemento de configuración con la clave especificada.

BaseGetAllKeys()

Devuelve una matriz de claves para todos los elementos de configuración incluidos en la colección ConfigurationElementCollection.

BaseGetKey(Int32)

Obtiene la clave para el objeto ConfigurationElement en la ubicación de índice especificada.

BaseIndexOf(ConfigurationElement)

Indica el índice del objeto ConfigurationElement especificado.

BaseIsRemoved(Object)

Indica si el objeto ConfigurationElement con la clave especificada se ha quitado de la colección ConfigurationElementCollection.

BaseRemove(Object)

Quita un objeto ConfigurationElement de la colección.

BaseRemoveAt(Int32)

Quita el objeto ConfigurationElement en la ubicación de índice especificada.

CopyTo(ConfigurationElement[], Int32)

Copia el contenido de la colección ConfigurationElementCollection en una matriz.

CreateNewElement()

Cuando se reemplaza en una clase derivada, se crea un nuevo objeto ConfigurationElement.

CreateNewElement(String)

Crea un nuevo objeto ConfigurationElement cuando se reemplaza en una clase derivada.

DeserializeElement(XmlReader, Boolean)

Lee XML del archivo de configuración.

(Heredado de ConfigurationElement)
Equals(Object)

Compara la colección ConfigurationElementCollection con el objeto especificado.

GetElementKey(ConfigurationElement)

Cuando se reemplaza en una clase derivada, obtiene la clave de elemento para un elemento de configuración especificado.

GetEnumerator()

Obtiene una interfaz IEnumerator que se utiliza para recorrer en iteración la colección ConfigurationElementCollection.

GetHashCode()

Obtiene un valor único que representa la instancia de ConfigurationElementCollection.

GetTransformedAssemblyString(String)

Devuelve la versión transformada del nombre de ensamblado especificado.

(Heredado de ConfigurationElement)
GetTransformedTypeString(String)

Devuelve la versión transformada del nombre de tipo especificado.

(Heredado de ConfigurationElement)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
Init()

Establece el objeto ConfigurationElement en su estado inicial.

(Heredado de ConfigurationElement)
InitializeDefault()

Se utiliza para inicializar un conjunto predeterminado de valores para el objeto ConfigurationElement.

(Heredado de ConfigurationElement)
IsElementName(String)

Indica si el objeto ConfigurationElement especificado existe en la colección ConfigurationElementCollection.

IsElementRemovable(ConfigurationElement)

Indica si la ConfigurationElement se puede quitar de ConfigurationElementCollection.

IsModified()

Indica si se ha modificado esta colección ConfigurationElementCollection desde la última vez en que se guardo o cargó al reemplazarla en una clase derivada.

IsReadOnly()

Indica si la el objeto ConfigurationElementCollection es de solo lectura.

ListErrors(IList)

Agrega a la lista que se pasa los errores de propiedad no válida que hay en este objeto ConfigurationElement y en todos los subelementos.

(Heredado de ConfigurationElement)
MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
OnDeserializeUnrecognizedAttribute(String, String)

Obtiene un valor que indica si se ha encontrado un atributo desconocido durante la deserialización.

(Heredado de ConfigurationElement)
OnDeserializeUnrecognizedElement(String, XmlReader)

Hace que el sistema de configuración produzca una excepción.

OnRequiredPropertyNotFound(String)

Se inicia una excepción cuando no se encuentra una propiedad necesaria.

(Heredado de ConfigurationElement)
PostDeserialize()

Se llama a este método después de la deserialización.

(Heredado de ConfigurationElement)
PreSerialize(XmlWriter)

Se llama a este método antes de la serialización.

(Heredado de ConfigurationElement)
Reset(ConfigurationElement)

Restablece la colección ConfigurationElementCollection a su estado sin modificaciones cuando se reemplaza en una clase derivada.

ResetModified()

Restablece el valor de la propiedad IsModified() en false cuando se invalida en una clase derivada.

SerializeElement(XmlWriter, Boolean)

Escribe los datos de configuración en un elemento XML del archivo de configuración cuando se reemplaza en una clase derivada.

SerializeToXmlElement(XmlWriter, String)

Escribe las etiquetas externas de este elemento de configuración en el archivo de configuración cuando se implementa en una clase derivada.

(Heredado de ConfigurationElement)
SetPropertyValue(ConfigurationProperty, Object, Boolean)

Establece una propiedad en el valor especificado.

(Heredado de ConfigurationElement)
SetReadOnly()

Establece la propiedad IsReadOnly() para el objeto ConfigurationElementCollection y para todos los subelementos.

ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)
Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode)

Invierte el efecto de combinar la información de configuración de distintos niveles de la jerarquía de configuración.

Implementaciones de interfaz explícitas

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 6, 7, 8, 9
.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
.NET Standard 2.0
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9

Consulte también