ConfigurationElementCollection Classe

Définition

Représente un élément de configuration contenant une collection d’éléments enfants.

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
Héritage
ConfigurationElementCollection
Dérivé
Implémente

Exemples

L’exemple suivant montre comment utiliser le ConfigurationElementCollection.

Le premier exemple se compose de trois classes : UrlsSection, UrlsCollection et UrlConfigElement. La UrlsSection classe utilise pour ConfigurationCollectionAttribute définir une section de configuration personnalisée. Cette section contient une collection d’URL (définie par la UrlsCollection classe) d’éléments URL (définis par la UrlConfigElement classe ).

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

Ce deuxième exemple de code utilise les classes spécifiées précédemment. Vous combinez ces deux exemples dans un projet d’application console.

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

Lorsque vous exécutez l’application console, une instance de la UrlsSection classe est créée et les éléments de configuration suivants sont générés dans le fichier de configuration de l’application :

<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  

Remarques

représente ConfigurationElementCollection une collection d’éléments dans un fichier de configuration.

Notes

Un élément dans un fichier de configuration fait référence à un élément XML de base ou à une section. Un élément simple est une balise XML avec des attributs associés, le cas échéant. Un élément simple constitue une section. Les sections complexes peuvent contenir un ou plusieurs éléments simples, une collection d’éléments et d’autres sections.

Vous utilisez pour ConfigurationElementCollection utiliser une collection d’objets ConfigurationElement . Implémentez cette classe pour ajouter des collections d’éléments personnalisés ConfigurationElement à un ConfigurationSection.

Notes pour les responsables de l’implémentation

Vous pouvez utiliser un modèle de codage programmatique ou déclaratif (avec attributs) pour créer un élément de configuration personnalisé.

Le modèle programmatique nécessite que pour chaque attribut d’élément, vous créez une propriété pour obtenir et définir sa valeur, et que vous l’ajoutez au conteneur de propriétés interne de la classe de base sous-jacente ConfigurationElement .

Le modèle déclaratif, également appelé modèle à attributs, vous permet de définir un attribut d’élément à l’aide d’une propriété et de le configurer avec des attributs. Ces attributs indiquent au système de configuration ASP.NET les types de propriétés et leurs valeurs par défaut. ASP.NET pouvez utiliser la réflexion pour obtenir ces informations, puis créer les objets de propriété d’élément et effectuer l’initialisation requise.

Constructeurs

ConfigurationElementCollection()

Initialise une nouvelle instance de la classe ConfigurationElementCollection.

ConfigurationElementCollection(IComparer)

Crée une instance de la classe ConfigurationElementCollection.

Propriétés

AddElementName

Obtient ou définit le nom du ConfigurationElement à associer à l'opération d'ajout dans ConfigurationElementCollection en cas de substitution dans une classe dérivée.

ClearElementName

Obtient ou définit le nom du ConfigurationElement à associer à l'opération d'effacement dans ConfigurationElementCollection en cas de substitution dans une classe dérivée.

CollectionType

Obtient le type de ConfigurationElementCollection.

Count

Obtient le nombre d’éléments de la collection.

CurrentConfiguration

Obtient une référence à l'instance Configuration de niveau supérieur qui représente la hiérarchie de configuration à laquelle l'instance ConfigurationElement actuelle appartient.

(Hérité de ConfigurationElement)
ElementInformation

Obtient un objet ElementInformation qui contient les fonctionnalités et informations non personnalisables de l'objet ConfigurationElement.

(Hérité de ConfigurationElement)
ElementName

Obtient le nom utilisé pour identifier cette collection d'éléments dans le fichier de configuration en cas de substitution dans une classe dérivée.

ElementProperty

Obtient l'objet ConfigurationElementProperty qui représente l'objet ConfigurationElement lui-même.

(Hérité de ConfigurationElement)
EmitClear

Obtient ou définit une valeur qui spécifie si la collection a été effacée.

EvaluationContext

Obtient l'objet ContextInformation pour l'objet ConfigurationElement.

(Hérité de ConfigurationElement)
HasContext

Obtient une valeur qui indique si la propriété CurrentConfiguration a la valeur null.

(Hérité de ConfigurationElement)
IsSynchronized

Obtient une valeur qui indique si l'accès à la collection est synchronisé.

Item[ConfigurationProperty]

Obtient ou définit une propriété ou un attribut de cet élément de configuration.

(Hérité de ConfigurationElement)
Item[String]

Obtient ou définit une propriété, un attribut ou un élément enfant de cet élément de configuration.

(Hérité de ConfigurationElement)
LockAllAttributesExcept

Obtient la collection d'attributs verrouillés.

(Hérité de ConfigurationElement)
LockAllElementsExcept

Obtient la collection d'éléments verrouillés.

(Hérité de ConfigurationElement)
LockAttributes

Obtient la collection d'attributs verrouillés.

(Hérité de ConfigurationElement)
LockElements

Obtient la collection d'éléments verrouillés.

(Hérité de ConfigurationElement)
LockItem

Obtient ou définit une valeur indiquant si l'élément est verrouillé.

(Hérité de ConfigurationElement)
Properties

Obtient la collection de propriétés.

(Hérité de ConfigurationElement)
RemoveElementName

Obtient ou définit le nom du ConfigurationElement à associer à l'opération de suppression dans ConfigurationElementCollection en cas de substitution dans une classe dérivée.

SyncRoot

Obtient un objet utilisé pour synchroniser l'accès à ConfigurationElementCollection.

ThrowOnDuplicate

Obtient une valeur indiquant si une tentative d'ajout d'un ConfigurationElement dupliqué à ConfigurationElementCollection provoquera la levée d'une exception.

Méthodes

BaseAdd(ConfigurationElement)

Ajoute un élément de configuration à ConfigurationElementCollection.

BaseAdd(ConfigurationElement, Boolean)

Ajoute un élément de configuration à la collection d'éléments de configuration.

BaseAdd(Int32, ConfigurationElement)

Ajoute un élément de configuration à la collection d'éléments de configuration.

BaseClear()

Supprime tous les objets d'élément de configuration de la collection.

BaseGet(Int32)

Obtient l'élément de configuration à l'emplacement d'index spécifié.

BaseGet(Object)

Retourne l'élément de configuration avec la clé spécifiée.

BaseGetAllKeys()

Retourne un tableau des clés pour tous les éléments de configuration contenus dans ConfigurationElementCollection.

BaseGetKey(Int32)

Obtient la clé pour le ConfigurationElement à l'emplacement d'index spécifié.

BaseIndexOf(ConfigurationElement)

Indique l'index de l'élément ConfigurationElement spécifié.

BaseIsRemoved(Object)

Indique si l'élément ConfigurationElement avec la clé spécifiée a été supprimé de la collection ConfigurationElementCollection.

BaseRemove(Object)

Supprime ConfigurationElement de la collection.

BaseRemoveAt(Int32)

Supprime le ConfigurationElement à l'emplacement d'index spécifié.

CopyTo(ConfigurationElement[], Int32)

Copie le contenu de ConfigurationElementCollection dans un tableau.

CreateNewElement()

En cas de substitution dans une classe dérivée, crée ConfigurationElement.

CreateNewElement(String)

Crée un nouveau ConfigurationElement en cas de substitution dans une classe dérivée.

DeserializeElement(XmlReader, Boolean)

Lit du XML à partir du fichier de configuration.

(Hérité de ConfigurationElement)
Equals(Object)

Compare ConfigurationElementCollection avec l'objet spécifié.

GetElementKey(ConfigurationElement)

Obtient la clé d'élément pour un élément de configuration spécifié en cas de substitution dans une classe dérivée.

GetEnumerator()

Obtient un IEnumerator utilisé pour itérer au sein de ConfigurationElementCollection.

GetHashCode()

Obtient une valeur unique représentant l'instance de ConfigurationElementCollection.

GetTransformedAssemblyString(String)

Retourne la version transformée du nom de l'assembly spécifié.

(Hérité de ConfigurationElement)
GetTransformedTypeString(String)

Retourne la version transformée du nom de type spécifié.

(Hérité de ConfigurationElement)
GetType()

Obtient le Type de l'instance actuelle.

(Hérité de Object)
Init()

Rétablit l’état initial de l’objet ConfigurationElement.

(Hérité de ConfigurationElement)
InitializeDefault()

Utilisé pour initialiser un jeu de valeurs par défaut pour l'objet ConfigurationElement.

(Hérité de ConfigurationElement)
IsElementName(String)

Indique si le ConfigurationElement spécifié existe dans ConfigurationElementCollection.

IsElementRemovable(ConfigurationElement)

Indique si l'élément ConfigurationElement spécifié peut être supprimée de la collection ConfigurationElementCollection.

IsModified()

Indique si cette ConfigurationElementCollection a été modifiée depuis son dernier enregistrement ou chargement en cas de substitution dans une classe dérivée.

IsReadOnly()

Indique si l'objet ConfigurationElementCollection est en lecture seule.

ListErrors(IList)

Ajoute les erreurs de propriété non valide dans cet objet ConfigurationElement et dans tous les sous-éléments à la liste passée.

(Hérité de ConfigurationElement)
MemberwiseClone()

Crée une copie superficielle du Object actuel.

(Hérité de Object)
OnDeserializeUnrecognizedAttribute(String, String)

Obtient une valeur indiquant si un attribut inconnu est rencontré pendant la désérialisation.

(Hérité de ConfigurationElement)
OnDeserializeUnrecognizedElement(String, XmlReader)

Fait en sorte que le système de configuration lève une exception.

OnRequiredPropertyNotFound(String)

Lève une exception lorsqu'une propriété requise est introuvable.

(Hérité de ConfigurationElement)
PostDeserialize()

Appelé après la désérialisation.

(Hérité de ConfigurationElement)
PreSerialize(XmlWriter)

Appelé avant la sérialisation.

(Hérité de ConfigurationElement)
Reset(ConfigurationElement)

Réinitialise ConfigurationElementCollection à son état non modifié en cas de substitution dans une classe dérivée.

ResetModified()

Réinitialise la valeur de la propriété IsModified() à false en cas de substitution dans une classe dérivée.

SerializeElement(XmlWriter, Boolean)

Écrit les données de configuration d'un élément XML dans le fichier de configuration en cas de substitution dans une classe dérivée.

SerializeToXmlElement(XmlWriter, String)

Écrit les balises extérieures de cet élément de configuration dans le fichier de configuration lorsqu'il est implémenté dans une classe dérivée.

(Hérité de ConfigurationElement)
SetPropertyValue(ConfigurationProperty, Object, Boolean)

Affecte la valeur spécifiée à une propriété.

(Hérité de ConfigurationElement)
SetReadOnly()

Définit la propriété IsReadOnly() pour l'objet ConfigurationElementCollection et pour tous les sous-éléments.

ToString()

Retourne une chaîne qui représente l'objet actuel.

(Hérité de Object)
Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode)

Inverse l'effet de la fusion des informations de configuration de différents niveaux de la hiérarchie de configuration.

Implémentations d’interfaces explicites

ICollection.CopyTo(Array, Int32)

Copie ConfigurationElementCollection dans un tableau.

Méthodes d’extension

Cast<TResult>(IEnumerable)

Effectue un cast des éléments d'un IEnumerable vers le type spécifié.

OfType<TResult>(IEnumerable)

Filtre les éléments d'un IEnumerable en fonction du type spécifié.

AsParallel(IEnumerable)

Active la parallélisation d'une requête.

AsQueryable(IEnumerable)

Convertit un IEnumerable en IQueryable.

S’applique à

Voir aussi