ConfigurationElementCollection Classe

Definição

Representa um elemento de configuração que contém uma coleção de elementos filho.Represents a configuration element containing a collection of child elements.

public ref class ConfigurationElementCollection abstract : System::Configuration::ConfigurationElement, System::Collections::ICollection
public abstract class ConfigurationElementCollection : System.Configuration.ConfigurationElement, System.Collections.ICollection
type ConfigurationElementCollection = class
    inherit ConfigurationElement
    interface ICollection
    interface IEnumerable
Public MustInherit Class ConfigurationElementCollection
Inherits ConfigurationElement
Implements ICollection
Herança
ConfigurationElementCollection
Derivado
Implementações

Exemplos

O exemplo a seguir mostra como usar o ConfigurationElementCollection.The following example shows how to use the ConfigurationElementCollection.

O primeiro exemplo consiste em três classes: UrlsSection UrlsCollection e UrlConfigElement. A UrlsSection classe usa o ConfigurationCollectionAttribute para definir uma seção de configuração personalizada.The first example consists of three classes: UrlsSection, UrlsCollection and UrlConfigElement.The UrlsSection class uses the ConfigurationCollectionAttribute to define a custom configuration section. Esta seção contém uma coleção de URLs (definida pela UrlsCollection classe) de elementos de URL (definida UrlConfigElement pela classe).This section contains a URL collection (defined by the UrlsCollection class) of URL elements (defined by the UrlConfigElement class).

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;
        }
    }
    
}
Imports System.Configuration

' Define a UrlsSection custom section that contains a 
' UrlsCollection collection of UrlConfigElement elements.
Public Class UrlsSection
    Inherits ConfigurationSection

    ' Declare the UrlsCollection collection property.
    <ConfigurationProperty("urls", IsDefaultCollection:=False), ConfigurationCollection(GetType(UrlsCollection), AddItemName:="add", ClearItemsName:="clear", RemoveItemName:="remove")>
    Public Property Urls() As UrlsCollection
        Get
            Dim urlsCollection As UrlsCollection = CType(MyBase.Item("urls"), UrlsCollection)

            Return urlsCollection
        End Get

        Set(ByVal value As UrlsCollection)
            Dim urlsCollection As UrlsCollection = value
        End Set

    End Property

    ' 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 Sub New()
        Dim url As New UrlConfigElement()
        Urls.Add(url)

    End Sub

End Class

' Define the UrlsCollection that contains the 
' UrlsConfigElement elements.
' This class shows how to use the ConfigurationElementCollection.
Public Class UrlsCollection
    Inherits System.Configuration.ConfigurationElementCollection


    Public Sub New()

    End Sub

    Public ReadOnly Property CollectionType() As ConfigurationElementCollectionType
        Get
            Return ConfigurationElementCollectionType.AddRemoveClearMap
        End Get
    End Property

    Protected Overloads Overrides Function CreateNewElement() As ConfigurationElement
        Return New UrlConfigElement()
    End Function

    Protected Overrides Function GetElementKey(ByVal element As ConfigurationElement) As Object
        Return (CType(element, UrlConfigElement)).Name
    End Function

    Default Public Shadows Property Item(ByVal index As Integer) As UrlConfigElement
        Get
            Return CType(BaseGet(index), UrlConfigElement)
        End Get
        Set(ByVal value As UrlConfigElement)
            If BaseGet(index) IsNot Nothing Then
                BaseRemoveAt(index)
            End If
            BaseAdd(value)
        End Set
    End Property

    Default Public Shadows ReadOnly Property Item(ByVal Name As String) As UrlConfigElement
        Get
            Return CType(BaseGet(Name), UrlConfigElement)
        End Get
    End Property

    Public Function IndexOf(ByVal url As UrlConfigElement) As Integer
        Return BaseIndexOf(url)
    End Function

    Public Sub Add(ByVal url As UrlConfigElement)
        BaseAdd(url)

        ' Your custom code goes here.

    End Sub

    Protected Overloads Sub BaseAdd(ByVal element As ConfigurationElement)
        BaseAdd(element, False)

        ' Your custom code goes here.

    End Sub

    Public Sub Remove(ByVal url As UrlConfigElement)
        If BaseIndexOf(url) >= 0 Then
            BaseRemove(url.Name)
            ' Your custom code goes here.
            Console.WriteLine("UrlsCollection: {0}", "Removed collection element!")
        End If
    End Sub

    Public Sub RemoveAt(ByVal index As Integer)
        BaseRemoveAt(index)

        ' Your custom code goes here.

    End Sub

    Public Sub Remove(ByVal name As String)
        BaseRemove(name)

        ' Your custom code goes here.

    End Sub

    Public Sub Clear()
        BaseClear()

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

End Class

' Define the UrlsConfigElement elements that are contained 
' by the UrlsCollection.
Public Class UrlConfigElement
    Inherits ConfigurationElement
    Public Sub New(ByVal name As String, ByVal url As String, ByVal port As Integer)
        Me.Name = name
        Me.Url = url
        Me.Port = port
    End Sub

    Public Sub New()

    End Sub

    <ConfigurationProperty("name", DefaultValue:="Contoso", IsRequired:=True, IsKey:=True)>
    Public Property Name() As String
        Get
            Return CStr(Me("name"))
        End Get
        Set(ByVal value As String)
            Me("name") = value
        End Set
    End Property

    <ConfigurationProperty("url", DefaultValue:="http://www.contoso.com", IsRequired:=True), RegexStringValidator("\w+:\/\/[\w.]+\S*")>
    Public Property Url() As String
        Get
            Return CStr(Me("url"))
        End Get
        Set(ByVal value As String)
            Me("url") = value
        End Set
    End Property

    <ConfigurationProperty("port", DefaultValue:=CInt(4040), IsRequired:=False), IntegerValidator(MinValue:=0, MaxValue:=8080, ExcludeRange:=False)>
    Public Property Port() As Integer
        Get
            Return CInt(Fix(Me("port")))
        End Get
        Set(ByVal value As Integer)
            Me("port") = value
        End Set
    End Property

End Class

Este segundo exemplo de código usa as classes especificadas anteriormente.This second code example uses the classes specified before. Você combina esses dois exemplos em um projeto de aplicativo de console.You combine these two examples in a console application project.

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();
        }
    }
}
Imports System.Configuration
Imports System.Text

Friend Class UsingConfigurationCollectionElement

    ' Create a custom section and save it in the 
    ' application configuration file.
    Private Shared Sub CreateCustomSection()
        Try

            ' Get the current configuration file.
            Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)

            ' Add the custom section to the application
            ' configuration file.
            Dim myUrlsSection As UrlsSection = CType(config.Sections("MyUrls"), UrlsSection)

            If myUrlsSection Is Nothing Then
                '  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 Then

                    ' The configuration file contains the
                    ' custom section but its element collection is empty.
                    ' Initialize the collection. 
                    Dim url As New UrlConfigElement()
                    myUrlsSection.Urls.Add(url)

                    ' Save the application configuration file.
                    myUrlsSection.SectionInformation.ForceSave = True
                    config.Save(ConfigurationSaveMode.Modified)
                End If
            End If


            Console.WriteLine("Created custom section in the application configuration file: {0}", config.FilePath)
            Console.WriteLine()

        Catch err As ConfigurationErrorsException
            Console.WriteLine("CreateCustomSection: {0}", err.ToString())
        End Try

    End Sub

    Private Shared Sub ReadCustomSection()
        Try
            ' Get the application configuration file.
            Dim config As System.Configuration.Configuration = TryCast(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None), Configuration)

            ' Read and display the custom section.
            Dim myUrlsSection As UrlsSection = TryCast(config.GetSection("MyUrls"), UrlsSection)

            If myUrlsSection Is Nothing Then
                Console.WriteLine("Failed to load UrlsSection.")
            Else
                Console.WriteLine("Collection elements contained in the custom section collection:")
                For i As Integer = 0 To myUrlsSection.Urls.Count - 1
                    Console.WriteLine("   Name={0} URL={1} Port={2}", myUrlsSection.Urls(i).Name, myUrlsSection.Urls(i).Url, myUrlsSection.Urls(i).Port)
                Next i
            End If

        Catch err As ConfigurationErrorsException
            Console.WriteLine("ReadCustomSection(string): {0}", err.ToString())
        End Try

    End Sub

    ' Add an element to the custom section collection.
    ' This function uses the ConfigurationCollectionElement Add method.
    Private Shared Sub AddCollectionElement()
        Try

            ' Get the current configuration file.
            Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)


            ' Get the custom configuration section.
            Dim myUrlsSection As UrlsSection = TryCast(config.GetSection("MyUrls"), UrlsSection)


            ' Add the element to the collection in the custom section.
            If config.Sections("MyUrls") IsNot Nothing Then
                Dim urlElement As 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.")
            End If

        Catch err As ConfigurationErrorsException
            Console.WriteLine("AddCollectionElement: {0}", err.ToString())
        End Try

    End Sub

    ' Remove element from the custom section collection.
    ' This function uses one of the ConfigurationCollectionElement 
    ' overloaded Remove methods.
    Private Shared Sub RemoveCollectionElement()
        Try

            ' Get the current configuration file.
            Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)


            ' Get the custom configuration section.
            Dim myUrlsSection As UrlsSection = TryCast(config.GetSection("MyUrls"), UrlsSection)


            ' Remove the element from the custom section.
            If config.Sections("MyUrls") IsNot Nothing Then
                Dim urlElement As 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.")
            End If

        Catch err As ConfigurationErrorsException
            Console.WriteLine("RemoveCollectionElement: {0}", err.ToString())
        End Try

    End Sub

    ' Remove the collection of elements from the custom section.
    ' This function uses the ConfigurationCollectionElement Clear method.
    Private Shared Sub ClearCollectionElements()
        Try

            ' Get the current configuration file.
            Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)


            ' Get the custom configuration section.
            Dim myUrlsSection As UrlsSection = TryCast(config.GetSection("MyUrls"), UrlsSection)


            ' Remove the collection of elements from the section.
            If config.Sections("MyUrls") IsNot Nothing Then
                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.")
            End If

        Catch err As ConfigurationErrorsException
            Console.WriteLine("ClearCollectionElements: {0}", err.ToString())
        End Try

    End Sub

    Public Shared Sub UserMenu()
        Dim applicationName As String = Environment.GetCommandLineArgs()(0) & ".exe"
        Dim buffer As 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())
    End Sub

    ' Obtain user's input and provide
    ' feedback.
    Shared Sub Main(ByVal args() As String)
        ' Define user selection string.
        Dim selection As String

        ' Get the name of the application.
        Dim appName As String = Environment.GetCommandLineArgs()(0)

        ' Get user selection.
        Do

            UserMenu()
            Console.Write("> ")
            selection = Console.ReadLine()
            If selection <> String.Empty Then
                Exit Do
            End If
        Loop

        Do While selection.ToLower() <> "q"
            ' Process user's input.
            Select Case selection
                Case "1"
                    ' Create a custom section and save it in the 
                    ' application configuration file.
                    CreateCustomSection()

                Case "2"
                    ' Read the custom section from the
                    ' application configuration file.
                    ReadCustomSection()

                Case "3"
                    ' Add a collection element to the
                    ' custom section.
                    AddCollectionElement()

                Case "4"
                    ' Remove a collection element from the
                    ' custom section.
                    RemoveCollectionElement()

                Case "5"
                    ' Clear the collection of elements from the
                    ' custom section.
                    ClearCollectionElements()

                Case Else
                    UserMenu()
            End Select
            Console.Write("> ")
            selection = Console.ReadLine()
        Loop
    End Sub
End Class

Quando você executa o aplicativo de console, uma instância da UrlsSection classe é criada e os seguintes elementos de configuração são gerados no arquivo de configuração do aplicativo:When you run the console application, an instance of the UrlsSection class is created and the following configuration elements are generated in the application configuration file:

<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  

Comentários

O ConfigurationElementCollection representa uma coleção de elementos dentro de um arquivo de configuração.The ConfigurationElementCollection represents a collection of elements within a configuration file.

Observação

Um elemento em um arquivo de configuração refere-se a um elemento XML básico ou uma seção.An element within a configuration file refers to a basic XML element or a section. Um elemento simples é uma marca XML com atributos relacionados, se houver.A simple element is an XML tag with related attributes, if any. Um elemento simples constitui uma seção.A simple element constitutes a section. Seções complexas podem conter um ou mais elementos simples, uma coleção de elementos e outras seções.Complex sections can contain one or more simple elements, a collection of elements, and other sections.

Use o ConfigurationElementCollection para trabalhar com uma coleção de ConfigurationElement objetos.You use the ConfigurationElementCollection to work with a collection of ConfigurationElement objects. Implemente essa classe para adicionar coleções de ConfigurationElement elementos personalizados a ConfigurationSectionum.Implement this class to add collections of custom ConfigurationElement elements to a ConfigurationSection.

Notas aos Implementadores

Você pode usar um modelo de codificação programático ou declarativo (atribuído) para criar um elemento de configuração personalizado.You can use a programmatic or a declarative (attributed) coding model to create a custom configuration element.

O modelo programático requer que, para cada atributo de elemento, você crie uma propriedade para obter e defina seu valor e a adicione ao recipiente de propriedades internas da classe ConfigurationElement base subjacente.The programmatic model requires that for each element attribute you create a property to get and set its value, and that you add it to the internal property bag of the underlying ConfigurationElement base class.

O modelo declarativo, também conhecido como modelo atribuído, permite que você defina um atributo de elemento usando uma propriedade e Configurando-o com atributos.The declarative model, also referred to as the attributed model, allows you to define an element attribute by using a property and configuring it with attributes. Esses atributos instruem o sistema de configuração ASP.NET sobre os tipos de propriedade e seus valores padrão.These attributes instruct the ASP.NET configuration system about the property types and their default values. ASP.NET pode usar a reflexão para obter essas informações e criar os objetos de Propriedade do elemento e executar a inicialização necessária.ASP.NET can use reflection to obtain this information and then create the element property objects and perform the required initialization.

Construtores

ConfigurationElementCollection()

Inicializa uma nova instância da classe ConfigurationElementCollection.Initializes a new instance of the ConfigurationElementCollection class.

ConfigurationElementCollection(IComparer)

Cria uma nova instância da classe ConfigurationElementCollection.Creates a new instance of the ConfigurationElementCollection class.

Propriedades

AddElementName

Obtém ou define o nome do ConfigurationElement a ser associado à operação de adição no ConfigurationElementCollection quando substituído em uma classe derivada.Gets or sets the name of the ConfigurationElement to associate with the add operation in the ConfigurationElementCollection when overridden in a derived class.

ClearElementName

Obtém ou define o nome do ConfigurationElement a ser associado à operação de limpeza no ConfigurationElementCollection quando substituído em uma classe derivada.Gets or sets the name for the ConfigurationElement to associate with the clear operation in the ConfigurationElementCollection when overridden in a derived class.

CollectionType

Obtém o tipo do ConfigurationElementCollection.Gets the type of the ConfigurationElementCollection.

Count

Obtém o número de elementos na coleção.Gets the number of elements in the collection.

CurrentConfiguration

Obtém uma referência para a instância Configuration de nível superior que representa a hierarquia de configuração à qual a instância atual ConfigurationElement pertence.Gets a reference to the top-level Configuration instance that represents the configuration hierarchy that the current ConfigurationElement instance belongs to.

(Herdado de ConfigurationElement)
ElementInformation

Obtém um objeto ElementInformation que contém as informações não personalizáveis e a funcionalidade do objeto ConfigurationElement.Gets an ElementInformation object that contains the non-customizable information and functionality of the ConfigurationElement object.

(Herdado de ConfigurationElement)
ElementName

Obtém o nome usado para identificar esta coleção de elementos no arquivo de configuração quando substituído em uma classe derivada.Gets the name used to identify this collection of elements in the configuration file when overridden in a derived class.

ElementProperty

Obtém o objeto ConfigurationElementProperty que representa o próprio objeto ConfigurationElement.Gets the ConfigurationElementProperty object that represents the ConfigurationElement object itself.

(Herdado de ConfigurationElement)
EmitClear

Obtém ou define um valor que especifica se a coleção foi limpa.Gets or sets a value that specifies whether the collection has been cleared.

EvaluationContext

Obtém o objeto ContextInformation para o objeto ConfigurationElement.Gets the ContextInformation object for the ConfigurationElement object.

(Herdado de ConfigurationElement)
HasContext

Obtém um valor que indica se a propriedade CurrentConfiguration é null.Gets a value that indicates whether the CurrentConfiguration property is null.

(Herdado de ConfigurationElement)
IsSynchronized

Obtém um valor que indica se o acesso à coleção é sincronizado.Gets a value indicating whether access to the collection is synchronized.

Item[ConfigurationProperty]

Obtém ou define uma propriedade ou um atributo desse elemento de configuração.Gets or sets a property or attribute of this configuration element.

(Herdado de ConfigurationElement)
Item[String]

Obtém ou define uma propriedade, atributo ou elemento filho desse elemento de configuração.Gets or sets a property, attribute, or child element of this configuration element.

(Herdado de ConfigurationElement)
LockAllAttributesExcept

Obtém a coleção de atributos bloqueados.Gets the collection of locked attributes.

(Herdado de ConfigurationElement)
LockAllElementsExcept

Obtém a coleção de elementos bloqueados.Gets the collection of locked elements.

(Herdado de ConfigurationElement)
LockAttributes

Obtém a coleção de atributos bloqueados.Gets the collection of locked attributes.

(Herdado de ConfigurationElement)
LockElements

Obtém a coleção de elementos bloqueados.Gets the collection of locked elements.

(Herdado de ConfigurationElement)
LockItem

Obtém ou define um valor que indica se o elemento está bloqueado.Gets or sets a value indicating whether the element is locked.

(Herdado de ConfigurationElement)
Properties

Obtém a coleção de propriedades.Gets the collection of properties.

(Herdado de ConfigurationElement)
RemoveElementName

Obtém ou define o nome do ConfigurationElement a ser associado à operação de remoção no ConfigurationElementCollection quando substituído em uma classe derivada.Gets or sets the name of the ConfigurationElement to associate with the remove operation in the ConfigurationElementCollection when overridden in a derived class.

SyncRoot

Obtém um objeto usado para sincronizar o acesso ao ConfigurationElementCollection.Gets an object used to synchronize access to the ConfigurationElementCollection.

ThrowOnDuplicate

Obtém um valor que indica se uma tentativa de adicionar uma duplicata ConfigurationElement ao ConfigurationElementCollection fará com que uma exceção seja lançada.Gets a value indicating whether an attempt to add a duplicate ConfigurationElement to the ConfigurationElementCollection will cause an exception to be thrown.

Métodos

BaseAdd(ConfigurationElement)

Adiciona um elemento de configuração ao ConfigurationElementCollection.Adds a configuration element to the ConfigurationElementCollection.

BaseAdd(ConfigurationElement, Boolean)

Adiciona um elemento de configuração à coleção de elementos de configuração.Adds a configuration element to the configuration element collection.

BaseAdd(Int32, ConfigurationElement)

Adiciona um elemento de configuração à coleção de elementos de configuração.Adds a configuration element to the configuration element collection.

BaseClear()

Remove todos os objetos de elemento de configuração da coleção.Removes all configuration element objects from the collection.

BaseGet(Int32)

Obtém o elemento de configuração no local do índice especificado.Gets the configuration element at the specified index location.

BaseGet(Object)

Retorna o elemento de configuração com a chave especificada.Returns the configuration element with the specified key.

BaseGetAllKeys()

Retorna uma matriz das chaves para todos os elementos de configuração contidos no ConfigurationElementCollection.Returns an array of the keys for all of the configuration elements contained in the ConfigurationElementCollection.

BaseGetKey(Int32)

Obtém a chave para o ConfigurationElement no local do índice especificado.Gets the key for the ConfigurationElement at the specified index location.

BaseIndexOf(ConfigurationElement)

Indica o índice do ConfigurationElement especificado.Indicates the index of the specified ConfigurationElement.

BaseIsRemoved(Object)

Indica se o ConfigurationElement com a chave especificada foi removido do ConfigurationElementCollection.Indicates whether the ConfigurationElement with the specified key has been removed from the ConfigurationElementCollection.

BaseRemove(Object)

Remove um ConfigurationElement da coleção.Removes a ConfigurationElement from the collection.

BaseRemoveAt(Int32)

Remove o ConfigurationElement no local de índice especificado.Removes the ConfigurationElement at the specified index location.

CopyTo(ConfigurationElement[], Int32)

Copia o conteúdo do ConfigurationElementCollection para uma matriz.Copies the contents of the ConfigurationElementCollection to an array.

CreateNewElement()

Quando substituído em uma classe derivada, cria um novo ConfigurationElement.When overridden in a derived class, creates a new ConfigurationElement.

CreateNewElement(String)

Cria um novo ConfigurationElement quando substituído em uma classe derivada.Creates a new ConfigurationElement when overridden in a derived class.

DeserializeElement(XmlReader, Boolean)

Lê o XML do arquivo de configuração.Reads XML from the configuration file.

(Herdado de ConfigurationElement)
Equals(Object)

Compara o ConfigurationElementCollection ao objeto especificado.Compares the ConfigurationElementCollection to the specified object.

GetElementKey(ConfigurationElement)

Obtém a chave de elemento para um elemento de configuração especificado quando substituído em uma classe derivada.Gets the element key for a specified configuration element when overridden in a derived class.

GetEnumerator()

Obtém um IEnumerator que é usado para iterar por meio de ConfigurationElementCollection.Gets an IEnumerator which is used to iterate through the ConfigurationElementCollection.

GetHashCode()

Obtém um valor exclusivo que representa a instância ConfigurationElementCollection.Gets a unique value representing the ConfigurationElementCollection instance.

GetTransformedAssemblyString(String)

Retorna a versão transformada do nome do assembly especificado.Returns the transformed version of the specified assembly name.

(Herdado de ConfigurationElement)
GetTransformedTypeString(String)

Retorna a versão transformada do nome do tipo especificado.Returns the transformed version of the specified type name.

(Herdado de ConfigurationElement)
GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
Init()

Define o objeto ConfigurationElement para seu estado inicial.Sets the ConfigurationElement object to its initial state.

(Herdado de ConfigurationElement)
InitializeDefault()

Usado para inicializar um conjunto padrão de valores para o objeto ConfigurationElement.Used to initialize a default set of values for the ConfigurationElement object.

(Herdado de ConfigurationElement)
IsElementName(String)

Indica se o ConfigurationElement especificado existe no ConfigurationElementCollection.Indicates whether the specified ConfigurationElement exists in the ConfigurationElementCollection.

IsElementRemovable(ConfigurationElement)

Indica se o ConfigurationElement especificado pode ser removido de ConfigurationElementCollection.Indicates whether the specified ConfigurationElement can be removed from the ConfigurationElementCollection.

IsModified()

Indica se este ConfigurationElementCollection foi modificado desde a última vez em que foi salvo ou carregado quando substituído em uma classe derivada.Indicates whether this ConfigurationElementCollection has been modified since it was last saved or loaded when overridden in a derived class.

IsReadOnly()

Indica se o objeto ConfigurationElementCollection é somente leitura.Indicates whether the ConfigurationElementCollection object is read only.

ListErrors(IList)

Adiciona os erros de propriedade inválida deste objeto ConfigurationElement e de todos os subelementos à lista passada.Adds the invalid-property errors in this ConfigurationElement object, and in all subelements, to the passed list.

(Herdado de ConfigurationElement)
MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
OnDeserializeUnrecognizedAttribute(String, String)

Obtém um valor que indica se um atributo desconhecido é encontrado durante a desserialização.Gets a value indicating whether an unknown attribute is encountered during deserialization.

(Herdado de ConfigurationElement)
OnDeserializeUnrecognizedElement(String, XmlReader)

Faz com que o sistema de configuração lance uma exceção.Causes the configuration system to throw an exception.

OnRequiredPropertyNotFound(String)

Gera uma exceção quando uma propriedade necessária não é encontrada.Throws an exception when a required property is not found.

(Herdado de ConfigurationElement)
PostDeserialize()

Chamado depois da desserialização.Called after deserialization.

(Herdado de ConfigurationElement)
PreSerialize(XmlWriter)

Chamado antes da serialização.Called before serialization.

(Herdado de ConfigurationElement)
Reset(ConfigurationElement)

Redefine o ConfigurationElementCollection para seu estado inalterado quando substituído em uma classe derivada.Resets the ConfigurationElementCollection to its unmodified state when overridden in a derived class.

ResetModified()

Redefine o valor da propriedade IsModified() para false quando substituído em uma classe derivada.Resets the value of the IsModified() property to false when overridden in a derived class.

SerializeElement(XmlWriter, Boolean)

Grava os dados de configuração em um elemento XML no arquivo de configuração quando substituído em uma classe derivada.Writes the configuration data to an XML element in the configuration file when overridden in a derived class.

SerializeToXmlElement(XmlWriter, String)

Grava as marcas externas desse elemento de configuração no arquivo de configuração quando implementado em uma classe derivada.Writes the outer tags of this configuration element to the configuration file when implemented in a derived class.

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

Define uma propriedade para o valor especificado.Sets a property to the specified value.

(Herdado de ConfigurationElement)
SetReadOnly()

Define a propriedade IsReadOnly() para o objeto ConfigurationElementCollection e para todos os subelementos.Sets the IsReadOnly() property for the ConfigurationElementCollection object and for all sub-elements.

ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

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

Inverte o efeito da mesclagem de informações de configuração de diferentes níveis da hierarquia de configuração.Reverses the effect of merging configuration information from different levels of the configuration hierarchy.

Implantações explícitas de interface

ICollection.CopyTo(Array, Int32)

Copia o ConfigurationElementCollection para uma matriz.Copies the ConfigurationElementCollection to an array.

Métodos de Extensão

Cast<TResult>(IEnumerable)

Converte os elementos de um IEnumerable para o tipo especificado.Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

Filtra os elementos de um IEnumerable com base em um tipo especificado.Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

Habilita a paralelização de uma consulta.Enables parallelization of a query.

AsQueryable(IEnumerable)

Converte um IEnumerable em um IQueryable.Converts an IEnumerable to an IQueryable.

Aplica-se a

Veja também