ConfigurationElementCollection Classe

Definizione

Rappresenta un elemento di configurazione contenente una raccolta di oggetti figlio.

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
Ereditarietà
ConfigurationElementCollection
Derivato
Implementazioni

Esempio

Nell'esempio seguente viene illustrato come usare .ConfigurationElementCollection

Il primo esempio è costituito da tre classi: UrlsSectione UrlsCollectionUrlConfigElement. La UrlsSection classe usa per ConfigurationCollectionAttribute definire una sezione di configurazione personalizzata. Questa sezione contiene una raccolta di URL (definita dalla UrlsCollection classe ) di elementi URL (definiti dalla 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

Questo secondo esempio di codice usa le classi specificate in precedenza. Questi due esempi vengono combinati in un progetto di applicazione 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

Quando si esegue l'applicazione console, viene creata un'istanza della UrlsSection classe e nel file di configurazione dell'applicazione vengono generati gli elementi di configurazione seguenti:

<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  

Commenti

Rappresenta ConfigurationElementCollection una raccolta di elementi all'interno di un file di configurazione.

Nota

Un elemento all'interno di un file di configurazione fa riferimento a un elemento XML di base o a una sezione. Un elemento semplice è un tag XML con attributi correlati, se presenti. Un elemento semplice costituisce una sezione. Le sezioni complesse possono contenere uno o più elementi semplici, una raccolta di elementi e altre sezioni.

Utilizzare per ConfigurationElementCollection utilizzare una raccolta di ConfigurationElement oggetti . Implementare questa classe per aggiungere raccolte di elementi personalizzati ConfigurationElement a un oggetto ConfigurationSection.

Note per gli implementatori

È possibile usare un modello di codifica dichiarativo (con attributi) a livello di codice per creare un elemento di configurazione personalizzato.

Il modello programmatico richiede che per ogni attributo di elemento venga creata una proprietà per ottenere e impostare il relativo valore e aggiungerlo al contenitore di proprietà interno della classe di base sottostante ConfigurationElement .

Il modello dichiarativo, detto anche modello con attributi, consente di definire un attributo di elemento usando una proprietà e configurandolo con attributi. Questi attributi indicano al sistema di configurazione ASP.NET i tipi di proprietà e i relativi valori predefiniti. ASP.NET possibile usare la reflection per ottenere queste informazioni e quindi creare gli oggetti proprietà dell'elemento ed eseguire l'inizializzazione necessaria.

Costruttori

ConfigurationElementCollection()

Inizializza una nuova istanza della classe ConfigurationElementCollection.

ConfigurationElementCollection(IComparer)

Crea una nuova istanza della classe ConfigurationElementCollection.

Proprietà

AddElementName

Ottiene o imposta il nome della classe ConfigurationElement da associare all'operazione di aggiunta nella classe ConfigurationElementCollection quando viene sottoposto a override in un classe derivata.

ClearElementName

Ottiene o imposta il nome della classe ConfigurationElement da associare all'operazione di cancellazione nella classe ConfigurationElementCollection quando viene sottoposto a override in un classe derivata.

CollectionType

Ottiene il tipo di ConfigurationElementCollection.

Count

Ottiene il numero di elementi nella raccolta.

CurrentConfiguration

Ottiene un riferimento all'istanza di Configuration di livello superiore che rappresenta la gerarchia di configurazione cui appartiene l'istanza corrente di ConfigurationElement.

(Ereditato da ConfigurationElement)
ElementInformation

Ottiene un oggetto ElementInformation contenente le funzionalità e le informazioni non personalizzabili dell'oggetto ConfigurationElement.

(Ereditato da ConfigurationElement)
ElementName

Ottiene il nome utilizzato per identificare questo insieme di elementi nel file di configurazione quando è sottoposto a override in un classe derivata.

ElementProperty

Ottiene l'oggetto ConfigurationElementProperty che rappresenta l'oggetto ConfigurationElement stesso.

(Ereditato da ConfigurationElement)
EmitClear

Ottiene o imposta un valore che specifica se l'insieme è stato cancellato.

EvaluationContext

Ottiene l'oggetto ContextInformation per l'oggetto ConfigurationElement.

(Ereditato da ConfigurationElement)
HasContext

Ottiene un valore che indica se la proprietà CurrentConfiguration è null.

(Ereditato da ConfigurationElement)
IsSynchronized

Ottiene un valore che indica se l'accesso alla raccolta è sincronizzato.

Item[ConfigurationProperty]

Ottiene o imposta una proprietà o un attributo di questo elemento di configurazione.

(Ereditato da ConfigurationElement)
Item[String]

Ottiene o imposta una proprietà, un attributo o un elemento figlio di questo elemento di configurazione.

(Ereditato da ConfigurationElement)
LockAllAttributesExcept

Ottiene l'insieme di attributi bloccati.

(Ereditato da ConfigurationElement)
LockAllElementsExcept

Ottiene l'insieme di elementi bloccati.

(Ereditato da ConfigurationElement)
LockAttributes

Ottiene l'insieme di attributi bloccati.

(Ereditato da ConfigurationElement)
LockElements

Ottiene l'insieme di elementi bloccati.

(Ereditato da ConfigurationElement)
LockItem

Ottiene o imposta un valore che indica se l'elemento è bloccato.

(Ereditato da ConfigurationElement)
Properties

Ottiene la raccolta di proprietà.

(Ereditato da ConfigurationElement)
RemoveElementName

Ottiene o imposta il nome della classe ConfigurationElement da associare all'operazione di rimozione nella classe ConfigurationElementCollection quando viene sottoposto a override in un classe derivata.

SyncRoot

Ottiene un oggetto utilizzato per sincronizzare l'accesso alla classe ConfigurationElementCollection.

ThrowOnDuplicate

Ottiene un valore che indica se il tentativo di aggiungere una classe ConfigurationElement duplicata alla classe ConfigurationElementCollection genererà un'eccezione.

Metodi

BaseAdd(ConfigurationElement)

Aggiunge un elemento di configurazione a ConfigurationElementCollection.

BaseAdd(ConfigurationElement, Boolean)

Aggiunge un elemento di configurazione all'insieme di elementi di configurazione.

BaseAdd(Int32, ConfigurationElement)

Aggiunge un elemento di configurazione all'insieme di elementi di configurazione.

BaseClear()

Rimuove tutti gli oggetti dell'elemento di configurazione dall'insieme.

BaseGet(Int32)

Ottiene l'elemento di configurazione in corrispondenza della posizione di indice specificata.

BaseGet(Object)

Restituisce l'elemento di configurazione con la chiave specificata.

BaseGetAllKeys()

Restituisce una matrice delle chiavi di tutti gli elementi di configurazione inclusi nella classe ConfigurationElementCollection.

BaseGetKey(Int32)

Ottiene la chiave per la classe ConfigurationElement in corrispondenza della posizione di indice specificata.

BaseIndexOf(ConfigurationElement)

Indica l'indice della classe ConfigurationElement specificata.

BaseIsRemoved(Object)

Indica se la classe ConfigurationElement con la chiave specificata è stata rimossa dalla classe ConfigurationElementCollection.

BaseRemove(Object)

Rimuove un oggetto ConfigurationElement dalla raccolta.

BaseRemoveAt(Int32)

Rimuove la classe ConfigurationElement in corrispondenza della posizione di indice specificata.

CopyTo(ConfigurationElement[], Int32)

Copia il contenuto della classe ConfigurationElementCollection in una matrice.

CreateNewElement()

Quando è sottoposto a override in una classe derivata, crea un nuovo elemento ConfigurationElement.

CreateNewElement(String)

Crea una nuova classe ConfigurationElement quando è sottoposto a override in una classe derivata.

DeserializeElement(XmlReader, Boolean)

Legge il codice XML dal file di configurazione.

(Ereditato da ConfigurationElement)
Equals(Object)

Confronta la classe ConfigurationElementCollection con l'oggetto specificato.

GetElementKey(ConfigurationElement)

Ottiene la chiave per un elemento di configurazione specificato quando viene sottoposto a override in un classe derivata.

GetEnumerator()

Ottiene un'interfaccia IEnumerator utilizzata per scorrere la classe ConfigurationElementCollection.

GetHashCode()

Ottiene un valore univoco che rappresenta l'istanza di ConfigurationElementCollection.

GetTransformedAssemblyString(String)

Restituisce la versione trasformata del nome di assembly specificato.

(Ereditato da ConfigurationElement)
GetTransformedTypeString(String)

Restituisce la versione trasformata del nome del tipo specificato.

(Ereditato da ConfigurationElement)
GetType()

Ottiene l'oggetto Type dell'istanza corrente.

(Ereditato da Object)
Init()

Ripristina lo stato iniziale dell'oggetto ConfigurationElement.

(Ereditato da ConfigurationElement)
InitializeDefault()

Da utilizzare per inizializzare un insieme predefinito di valori per l'oggetto ConfigurationElement.

(Ereditato da ConfigurationElement)
IsElementName(String)

Indica se la classe ConfigurationElement specificata esiste nella classe ConfigurationElementCollection.

IsElementRemovable(ConfigurationElement)

Indica se è possibile rimuovere l'oggetto ConfigurationElement da ConfigurationElementCollection.

IsModified()

Indica se questa classe ConfigurationElementCollection è stata modificata dall'ultimo salvataggio o caricamento durante l'override in una classe derivata.

IsReadOnly()

Indica se l'oggetto ConfigurationElementCollection è in sola lettura.

ListErrors(IList)

Aggiunge all'elenco passato gli errori di proprietà non valida di questo oggetto ConfigurationElement e di tutti i sottoelementi.

(Ereditato da ConfigurationElement)
MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.

(Ereditato da Object)
OnDeserializeUnrecognizedAttribute(String, String)

Ottiene un valore che indica se viene incontrato un attributo sconosciuto durante la deserializzazione.

(Ereditato da ConfigurationElement)
OnDeserializeUnrecognizedElement(String, XmlReader)

Fa generare un'eccezione al sistema di configurazione.

OnRequiredPropertyNotFound(String)

Genera un'eccezione quando una proprietà obbligatoria non viene trovata.

(Ereditato da ConfigurationElement)
PostDeserialize()

Da chiamare dopo la deserializzazione.

(Ereditato da ConfigurationElement)
PreSerialize(XmlWriter)

Da chiamare prima della serializzazione.

(Ereditato da ConfigurationElement)
Reset(ConfigurationElement)

Reimposta la classe ConfigurationElementCollection sullo stato non modificato quando viene sottoposta a override in una classe derivata.

ResetModified()

Reimposta il valore della proprietà IsModified() su false quando viene sottoposto a override in una classe derivata.

SerializeElement(XmlWriter, Boolean)

Scrive i dati di configurazione in un elemento XML del file di configurazione quando vengono sottoposti a override in una classe derivata.

SerializeToXmlElement(XmlWriter, String)

Scrive i tag esterni di questo elemento di configurazione nel file di configurazione in caso di implementazione in una classe derivata.

(Ereditato da ConfigurationElement)
SetPropertyValue(ConfigurationProperty, Object, Boolean)

Imposta una proprietà sul valore specificato.

(Ereditato da ConfigurationElement)
SetReadOnly()

Imposta la proprietà IsReadOnly() per l'oggetto ConfigurationElementCollection e per tutti i sottoelementi.

ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)
Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode)

Inverte l'effetto di unione delle informazioni sulla configurazione da livelli diversi della gerarchia di configurazione.

Implementazioni dell'interfaccia esplicita

ICollection.CopyTo(Array, Int32)

Copia ConfigurationElementCollection in una matrice.

Metodi di estensione

Cast<TResult>(IEnumerable)

Esegue il cast degli elementi di un oggetto IEnumerable nel tipo specificato.

OfType<TResult>(IEnumerable)

Filtra gli elementi di un oggetto IEnumerable in base a un tipo specificato.

AsParallel(IEnumerable)

Consente la parallelizzazione di una query.

AsQueryable(IEnumerable)

Converte un oggetto IEnumerable in un oggetto IQueryable.

Si applica a

Vedi anche