ConfigurationElementCollection Klasse

Definition

Stellt ein Konfigurationselement dar, das eine Auflistung von untergeordneten Elementen enthält.

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
Vererbung
ConfigurationElementCollection
Abgeleitet
Implementiert

Beispiele

Im folgenden Beispiel wird gezeigt, wie sie verwendet werden ConfigurationElementCollection.

Das erste Beispiel besteht aus drei Klassen: UrlsSection, UrlsCollection und UrlConfigElement. Die UrlsSection -Klasse verwendet den ConfigurationCollectionAttribute , um einen benutzerdefinierten Konfigurationsabschnitt zu definieren. Dieser Abschnitt enthält eine URL-Auflistung (definiert durch die UrlsCollection -Klasse) von URL-Elementen (definiert durch die UrlConfigElement -Klasse).

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

In diesem zweiten Codebeispiel werden die zuvor angegebenen Klassen verwendet. Sie kombinieren diese beiden Beispiele in einem Konsolenanwendungsprojekt.

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

Wenn Sie die Konsolenanwendung ausführen, wird ein instance der UrlsSection -Klasse erstellt, und die folgenden Konfigurationselemente werden in der Anwendungskonfigurationsdatei generiert:

<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  

Hinweise

Stellt ConfigurationElementCollection eine Auflistung von Elementen in einer Konfigurationsdatei dar.

Hinweis

Ein Element in einer Konfigurationsdatei bezieht sich auf ein grundlegendes XML-Element oder einen Abschnitt. Ein einfaches Element ist ein XML-Tag mit verwandten Attributen, falls vorhanden. Ein einfaches Element stellt einen Abschnitt dar. Komplexe Abschnitte können ein oder mehrere einfache Elemente, eine Auflistung von Elementen und andere Abschnitte enthalten.

Verwenden Sie , ConfigurationElementCollection um mit einer Auflistung von ConfigurationElement -Objekten zu arbeiten. Implementieren Sie diese Klasse, um Sammlungen von benutzerdefinierten ConfigurationElement Elementen zu einer ConfigurationSectionhinzuzufügen.

Hinweise für Ausführende

Sie können ein programmgesteuertes oder ein deklaratives (attributiertes) Codierungsmodell verwenden, um ein benutzerdefiniertes Konfigurationselement zu erstellen.

Das programmgesteuerte Modell erfordert, dass Sie für jedes Elementattribute eine Eigenschaft erstellen, um ihren Wert abzurufen und festzulegen, und dass Sie sie dem internen Eigenschaftenbehälter der zugrunde liegenden ConfigurationElement Basisklasse hinzufügen.

Mit dem deklarativen Modell, das auch als attributiertes Modell bezeichnet wird, können Sie ein Elementattribute definieren, indem Sie eine Eigenschaft verwenden und es mit Attributen konfigurieren. Diese Attribute weisen das ASP.NET-Konfigurationssystem über die Eigenschaftentypen und deren Standardwerte an. ASP.NET können diese Informationen mithilfe von Reflektion abrufen und dann die Elementeigenschaftenobjekte erstellen und die erforderliche Initialisierung ausführen.

Konstruktoren

ConfigurationElementCollection()

Initialisiert eine neue Instanz der ConfigurationElementCollection-Klasse.

ConfigurationElementCollection(IComparer)

Erstellt eine neue Instanz der ConfigurationElementCollection-Klasse.

Eigenschaften

AddElementName

Ruft den Namen des ConfigurationElement ab, das beim Überschreiben in einer abgeleiteten Klasse dem Hinzufügevorgang in der ConfigurationElementCollection zugeordnet werden soll, oder legt diesen fest.

ClearElementName

Ruft den Namen für das ConfigurationElement ab, das beim Überschreiben in einer abgeleiteten Klasse dem Löschvorgang in der ConfigurationElementCollection zugeordnet werden soll, oder legt diesen fest.

CollectionType

Ruft den Typ des ConfigurationElementCollection ab.

Count

Ruft die Anzahl der Elemente in der Auflistung ab.

CurrentConfiguration

Ruft einen Verweis auf die Configuration-Instanz der obersten Ebene ab, die die Konfigurationshierarchie darstellt, zu der die aktuelle ConfigurationElement-Instanz gehört.

(Geerbt von ConfigurationElement)
ElementInformation

Ruft ein ElementInformation-Objekt ab, das die nicht anpassbaren Informationen und Funktionen des ConfigurationElement-Objekts enthält.

(Geerbt von ConfigurationElement)
ElementName

Ruft den Namen ab, der beim Überschreiben in einer abgeleiteten Klasse für die Identifikation dieser Auflistung mit Elementen in der Konfigurationsdatei verwendet wird.

ElementProperty

Ruft das ConfigurationElementProperty-Objekt ab, das das ConfigurationElement-Objekt selbst darstellt.

(Geerbt von ConfigurationElement)
EmitClear

Ruft einen Wert ab, der angibt, ob die Auflistung gelöscht wurde, oder legt diesen fest.

EvaluationContext

Ruft das ContextInformation-Objekt für das ConfigurationElement-Objekt ab.

(Geerbt von ConfigurationElement)
HasContext

Ruft einen Wert ab, der angibt, ob die CurrentConfiguration-Eigenschaft null ist.

(Geerbt von ConfigurationElement)
IsSynchronized

Ruft einen Wert ab, der angibt, ob der Zugriff auf die Auflistung synchronisiert ist.

Item[ConfigurationProperty]

Ruft eine Eigenschaft oder ein Attribut dieses Konfigurationselements ab oder legt diese bzw. dieses fest.

(Geerbt von ConfigurationElement)
Item[String]

Ruft eine Eigenschaft, ein Attribut oder ein untergeordnetes Element dieses Konfigurationselements ab oder legt diese(s) fest.

(Geerbt von ConfigurationElement)
LockAllAttributesExcept

Ruft die Auflistung gesperrter Attribute ab.

(Geerbt von ConfigurationElement)
LockAllElementsExcept

Ruft die Auflistung gesperrter Elemente ab.

(Geerbt von ConfigurationElement)
LockAttributes

Ruft die Auflistung gesperrter Attribute ab.

(Geerbt von ConfigurationElement)
LockElements

Ruft die Auflistung gesperrter Elemente ab.

(Geerbt von ConfigurationElement)
LockItem

Ruft einen Wert ab, der angibt, ob das Element gesperrt ist, oder legt diesen fest.

(Geerbt von ConfigurationElement)
Properties

Ruft die Auflistung von Eigenschaften ab.

(Geerbt von ConfigurationElement)
RemoveElementName

Ruft den Namen des ConfigurationElement ab, das beim Überschreiben in einer abgeleiteten Klasse dem Entfernungsvorgang in der ConfigurationElementCollection zugeordnet werden soll, oder legt diesen fest.

SyncRoot

Ruft ein Objekt ab, das zum Synchronisieren des Zugriffs auf ConfigurationElementCollection verwendet wird.

ThrowOnDuplicate

Ruft einen Wert ab, der angibt, ob der Versuch, der ConfigurationElement ein doppeltes ConfigurationElementCollection hinzuzufügen, eine Ausnahme auslöst.

Methoden

BaseAdd(ConfigurationElement)

Fügt der ConfigurationElementCollection ein Konfigurationselement hinzu.

BaseAdd(ConfigurationElement, Boolean)

Fügt der Konfigurationselementauflistung ein Konfigurationselement hinzu.

BaseAdd(Int32, ConfigurationElement)

Fügt der Konfigurationselementauflistung ein Konfigurationselement hinzu.

BaseClear()

Entfernt alle Konfigurationselementobjekte aus der Auflistung.

BaseGet(Int32)

Ruft das Konfigurationselement am angegebenen Index ab.

BaseGet(Object)

Gibt das Konfigurationselement mit dem angegebenen Schlüssel zurück.

BaseGetAllKeys()

Gibt ein Array der Schlüssel für alle Konfigurationselemente in der ConfigurationElementCollection zurück.

BaseGetKey(Int32)

Ruft den Schlüssel für das ConfigurationElement an der angegebenen Indexposition ab.

BaseIndexOf(ConfigurationElement)

Gibt den Index der angegebenen ConfigurationElement an.

BaseIsRemoved(Object)

Gibt an, ob das ConfigurationElement mit dem angegebenen Schlüssel aus der ConfigurationElementCollection entfernt worden ist.

BaseRemove(Object)

Entfernt ein ConfigurationElement aus der Auflistung.

BaseRemoveAt(Int32)

Entfernt das ConfigurationElement an der angegebenen Indexposition.

CopyTo(ConfigurationElement[], Int32)

Kopiert den Inhalt der ConfigurationElementCollection in ein Array.

CreateNewElement()

Erstellt beim Überschreiben in einer abgeleiteten Klasse einen neuen ConfigurationElement.

CreateNewElement(String)

Erstellt ein neues ConfigurationElement, wenn es in einer abgeleiteten Klasse überschrieben wurde.

DeserializeElement(XmlReader, Boolean)

Liest XML aus der Konfigurationsdatei.

(Geerbt von ConfigurationElement)
Equals(Object)

Vergleicht die ConfigurationElementCollection mit dem angegebenen Objekt.

GetElementKey(ConfigurationElement)

Ruft beim Überschreiben in einer abgeleiteten Klasse den Elementschlüssel für ein angegebenes Konfigurationselement ab.

GetEnumerator()

Ruft einen IEnumerator ab, der zum Durchlaufen von ConfigurationElementCollection verwendet wird.

GetHashCode()

Ruft einen eindeutigen Wert ab, der die ConfigurationElementCollection-Instanz darstellt.

GetTransformedAssemblyString(String)

Gibt die transformierte Version des angegebenen Assemblynamens zurück.

(Geerbt von ConfigurationElement)
GetTransformedTypeString(String)

Gibt die transformierte Version des angegebenen Typnamens zurück.

(Geerbt von ConfigurationElement)
GetType()

Ruft den Type der aktuellen Instanz ab.

(Geerbt von Object)
Init()

Legt für das ConfigurationElement-Objekt den Ausgangszustand fest.

(Geerbt von ConfigurationElement)
InitializeDefault()

Wird verwendet, um einen Standardsatz von Werten für das ConfigurationElement-Objekt zu initialisieren.

(Geerbt von ConfigurationElement)
IsElementName(String)

Gibt an, ob das angegebene ConfigurationElement in der ConfigurationElementCollection vorhanden ist.

IsElementRemovable(ConfigurationElement)

Gibt an, ob das angegebene ConfigurationElement aus der ConfigurationElementCollection entfernt werden kann.

IsModified()

Gibt an, ob diese ConfigurationElementCollection geändert wurde, seit sie zuletzt gespeichert oder geladen wurde, wenn sie in einer abgeleiteten Klasse überschrieben wurde.

IsReadOnly()

Gibt an, ob das ConfigurationElementCollection-Objekt schreibgeschützt ist.

ListErrors(IList)

Fügt die Fehler über ungültige Eigenschaften in diesem ConfigurationElement-Objekt und in allen Unterelementen der übergebenen Liste hinzu.

(Geerbt von ConfigurationElement)
MemberwiseClone()

Erstellt eine flache Kopie des aktuellen Object.

(Geerbt von Object)
OnDeserializeUnrecognizedAttribute(String, String)

Ruft einen Wert ab, der angibt, ob während der Deserialisierung ein unbekanntes Attribut aufgetreten ist.

(Geerbt von ConfigurationElement)
OnDeserializeUnrecognizedElement(String, XmlReader)

Bewirkt, dass das Konfigurationssystem eine Ausnahme auslöst.

OnRequiredPropertyNotFound(String)

Löst eine Ausnahme aus, wenn eine erforderliche Eigenschaft nicht gefunden wird.

(Geerbt von ConfigurationElement)
PostDeserialize()

Wird nach der Deserialisierung aufgerufen.

(Geerbt von ConfigurationElement)
PreSerialize(XmlWriter)

Wird vor der Serialisierung aufgerufen.

(Geerbt von ConfigurationElement)
Reset(ConfigurationElement)

Setzt die ConfigurationElementCollection auf ihren unveränderten Zustand zurück, wenn sie in einer abgeleiteten Klasse überschrieben wurde.

ResetModified()

Setzt den Wert der IsModified()-Eigenschaft auf false zurück, wenn er in einer abgeleiteten Klasse überschrieben wurde.

SerializeElement(XmlWriter, Boolean)

Schreibt die Konfigurationsdaten in ein XML-Element in der Konfigurationsdatei, wenn sie in einer abgeleiteten Klasse überschrieben wurden.

SerializeToXmlElement(XmlWriter, String)

Schreibt bei Implementierung in einer abgeleiteten Klasse die äußeren Tags dieses Konfigurationselements in die Konfigurationsdatei.

(Geerbt von ConfigurationElement)
SetPropertyValue(ConfigurationProperty, Object, Boolean)

Legt eine Eigenschaft auf den angegebenen Wert fest.

(Geerbt von ConfigurationElement)
SetReadOnly()

Legt die IsReadOnly()-Eigenschaft für das ConfigurationElementCollection-Objekt und alle Unterelemente fest.

ToString()

Gibt eine Zeichenfolge zurück, die das aktuelle Objekt darstellt.

(Geerbt von Object)
Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode)

Kehrt die Auswirkungen der Zusammenführung von Konfigurationsinformationen aus verschiedenen Ebenen der Konfigurationshierarchie um.

Explizite Schnittstellenimplementierungen

ICollection.CopyTo(Array, Int32)

Kopiert das ConfigurationElementCollection in ein Array.

Erweiterungsmethoden

Cast<TResult>(IEnumerable)

Wandelt die Elemente eines IEnumerable in den angegebenen Typ um

OfType<TResult>(IEnumerable)

Filtert die Elemente eines IEnumerable anhand eines angegebenen Typs

AsParallel(IEnumerable)

Ermöglicht die Parallelisierung einer Abfrage.

AsQueryable(IEnumerable)

Konvertiert einen IEnumerable in einen IQueryable.

Gilt für:

Weitere Informationen