ConfigurationElementCollection 클래스

정의

자식 요소의 컬렉션을 포함하는 구성 요소를 나타냅니다.Represents a configuration element containing a collection of child elements.

public ref class ConfigurationElementCollection abstract : System::Configuration::ConfigurationElement, System::Collections::ICollection
public abstract class ConfigurationElementCollection : System.Configuration.ConfigurationElement, System.Collections.ICollection
type ConfigurationElementCollection = class
    inherit ConfigurationElement
    interface ICollection
    interface IEnumerable
Public MustInherit Class ConfigurationElementCollection
Inherits ConfigurationElement
Implements ICollection
상속
ConfigurationElementCollection
파생
구현

예제

다음 예제에서는 사용 하는 방법의 ConfigurationElementCollection합니다.The following example shows how to use the ConfigurationElementCollection.

첫 번째 예제에서는 세 가지 클래스로 구성 됩니다. UrlsSection, UrlsCollectionUrlConfigElement입니다. 합니다 UrlsSection 클래스가 사용 하는 ConfigurationCollectionAttribute 사용자 지정 구성 섹션을 정의 합니다.The first example consists of three classes: UrlsSection, UrlsCollection and UrlConfigElement.The UrlsSection class uses the ConfigurationCollectionAttribute to define a custom configuration section. 이 섹션에서는 URL 컬렉션을 포함 (정의한 합니다 UrlsCollection 클래스) URL 요소 (정의한는 UrlConfigElement 클래스).This section contains a URL collection (defined by the UrlsCollection class) of URL elements (defined by the UrlConfigElement class).

using System;
using System.Configuration;

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

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

            return urlsCollection;
        }

        set
        {
            UrlsCollection urlsCollection = value;
        }
    
    }

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

    }

}

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

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

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

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

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

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

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

        // Your custom code goes here.
       
    }

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

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

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

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

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

}

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

    public UrlConfigElement()
    {

    }

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

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

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

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

            Return urlsCollection
        End Get

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

    End Property

    ' Create a new instance of the UrlsSection.
    ' This constructor creates a configuration element 
    ' using the UrlConfigElement default values.
    ' It assigns this element to the collection.
    Public Sub New()
        Dim url As New UrlConfigElement()
        Urls.Add(url)

    End Sub

End Class

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


    Public Sub New()

    End Sub

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

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

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

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

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

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

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

        ' Your custom code goes here.

    End Sub

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

        ' Your custom code goes here.

    End Sub

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

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

        ' Your custom code goes here.

    End Sub

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

        ' Your custom code goes here.

    End Sub

    Public Sub Clear()
        BaseClear()

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

End Class

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

    Public Sub New()

    End Sub

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

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

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

End Class

이 두 번째 코드 예제에서는 앞에 지정 된 클래스를 사용 합니다.This second code example uses the classes specified before. 이러한 두 가지 예제 콘솔 애플리케이션 프로젝트에서를 결합 하는 있습니다.You combine these two examples in a console application project.

using System;
using System.Configuration;
using System.Text;

class UsingConfigurationCollectionElement
{

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

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

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

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

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

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

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

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

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

        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("CreateCustomSection: {0}", err.ToString());
        }

    }

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

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

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

        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("ReadCustomSection(string): {0}", err.ToString());
        }

    }

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

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


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


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

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

        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("AddCollectionElement: {0}", err.ToString());
        }

    }

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

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


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


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

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


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


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

        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("RemoveCollectionElement: {0}", err.ToString());
        }

    }

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

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


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


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


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


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

        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("ClearCollectionElements: {0}", err.ToString());
        }

    }

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

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

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

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

        // Get user selection.
        while (true)
        {

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

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

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

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

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

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

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

Friend Class UsingConfigurationCollectionElement

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

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

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

            If myUrlsSection Is Nothing Then
                '  The configuration file does not contain the
                ' custom section yet. Create it.
                myUrlsSection = New UrlsSection()

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

                ' Save the application configuration file.
                myUrlsSection.SectionInformation.ForceSave = True
                config.Save(ConfigurationSaveMode.Modified)
            Else
                If myUrlsSection.Urls.Count = 0 Then

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

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


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

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

    End Sub

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

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

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

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

    End Sub

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

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


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


            ' Add the element to the collection in the custom section.
            If config.Sections("MyUrls") IsNot Nothing Then
                Dim urlElement As New UrlConfigElement()
                urlElement.Name = "Microsoft"
                urlElement.Url = "http://www.microsoft.com"
                urlElement.Port = 8080

                ' Use the ConfigurationCollectionElement Add method
                ' to add the new element to the collection.
                myUrlsSection.Urls.Add(urlElement)


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


                Console.WriteLine("Added collection element to the custom section in the configuration file: {0}", config.FilePath)
                Console.WriteLine()
            Else
                Console.WriteLine("You must create the custom section first.")
            End If

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

    End Sub

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

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


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


            ' Remove the element from the custom section.
            If config.Sections("MyUrls") IsNot Nothing Then
                Dim urlElement As New UrlConfigElement()
                urlElement.Name = "Microsoft"
                urlElement.Url = "http://www.microsoft.com"
                urlElement.Port = 8080

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


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


                Console.WriteLine("Removed collection element from he custom section in the configuration file: {0}", config.FilePath)
                Console.WriteLine()
            Else
                Console.WriteLine("You must create the custom section first.")
            End If

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

    End Sub

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

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


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


            ' Remove the collection of elements from the section.
            If config.Sections("MyUrls") IsNot Nothing Then
                myUrlsSection.Urls.Clear()


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


                Console.WriteLine("Removed collection of elements from he custom section in the configuration file: {0}", config.FilePath)
                Console.WriteLine()
            Else
                Console.WriteLine("You must create the custom section first.")
            End If

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

    End Sub

    Public Shared Sub UserMenu()
        Dim applicationName As String = Environment.GetCommandLineArgs()(0) & ".exe"
        Dim buffer As New StringBuilder()

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

        Console.Write(buffer.ToString())
    End Sub

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

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

        ' Get user selection.
        Do

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

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

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

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

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

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

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

콘솔 애플리케이션의 인스턴스를 실행 하는 경우는 UrlsSection 클래스 생성 되 고 다음 구성 요소를 애플리케이션 구성 파일에서 생성 됩니다.When you run the console application, an instance of the UrlsSection class is created and the following configuration elements are generated in the application configuration file:

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

설명

ConfigurationElementCollection 구성 파일 내에서 요소의 컬렉션을 나타냅니다.The ConfigurationElementCollection represents a collection of elements within a configuration file.

참고

구성 파일 내의 요소는 기본 XML 요소 또는 섹션을 가리킵니다.An element within a configuration file refers to a basic XML element or a section. 단순 요소는 관련된 특성을 사용 하 여 XML 태그는 있는 경우.A simple element is an XML tag with related attributes, if any. 단순 요소 섹션을 구성합니다.A simple element constitutes a section. 복잡 한 섹션에는 하나 이상의 단순 요소, 요소, 컬렉션 및 다른 섹션 포함 될 수 있습니다.Complex sections can contain one or more simple elements, a collection of elements, and other sections.

사용할 합니다 ConfigurationElementCollection 컬렉션과 함께 작동 하도록 ConfigurationElement 개체입니다.You use the ConfigurationElementCollection to work with a collection of ConfigurationElement objects. 사용자 지정 컬렉션을 추가 하려면이 클래스를 구현 ConfigurationElement 요소를 사용 하는 ConfigurationSection합니다.Implement this class to add collections of custom ConfigurationElement elements to a ConfigurationSection.

구현자 참고

프로그래밍 방식으로 또는 선언적 (특성 사용된) 코딩 모델 사용자 지정 구성 요소를 만드는 데 사용할 수 있습니다.You can use a programmatic or a declarative (attributed) coding model to create a custom configuration element.

각 요소의 특성에 대 한 사용자가 만든 가져오고 해당 값을 설정 하는 속성 및 기본의 내부 속성 모음에 추가 하는 프로그래밍 모델에서는 ConfigurationElement 기본 클래스입니다.The programmatic model requires that for each element attribute you create a property to get and set its value, and that you add it to the internal property bag of the underlying ConfigurationElement base class.

선언적 모델을 라고도 특성이 지정 된 모델 속성을 사용 하 여 특성을 사용 하 여 구성 요소 특성을 정의할 수 있습니다.The declarative model, also referred to as the attributed model, allows you to define an element attribute by using a property and configuring it with attributes. 이러한 특성은 속성 형식과 해당 기본값에 대 한 ASP.NET 구성 시스템을 지시합니다.These attributes instruct the ASP.NET configuration system about the property types and their default values. ASP.NET는 리플렉션을 사용 하 여이 정보를 가져올 및 다음 요소 속성 개체를 만들고 필요한 초기화를 수행할 수 있습니다.ASP.NET can use reflection to obtain this information and then create the element property objects and perform the required initialization.

생성자

ConfigurationElementCollection()

ConfigurationElementCollection 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the ConfigurationElementCollection class.

ConfigurationElementCollection(IComparer)

ConfigurationElementCollection 클래스의 새 인스턴스를 만듭니다.Creates a new instance of the ConfigurationElementCollection class.

속성

AddElementName

파생 클래스에서 재정의될 때 ConfigurationElement의 추가 작업과 연결할 ConfigurationElementCollection의 이름을 가져오거나 설정합니다.Gets or sets the name of the ConfigurationElement to associate with the add operation in the ConfigurationElementCollection when overridden in a derived class.

ClearElementName

파생 클래스에서 재정의될 때 ConfigurationElement의 지우기 작업과 연결할 ConfigurationElementCollection의 이름을 가져오거나 설정합니다.Gets or sets the name for the ConfigurationElement to associate with the clear operation in the ConfigurationElementCollection when overridden in a derived class.

CollectionType

ConfigurationElementCollection의 형식을 가져옵니다.Gets the type of the ConfigurationElementCollection.

Count

컬렉션의 요소 수를 가져옵니다.Gets the number of elements in the collection.

CurrentConfiguration

현재 Configuration 인스턴스가 속해 있는 구성 계층 구조를 나타내는 최상위 ConfigurationElement 인스턴스에 대한 참조를 가져옵니다.Gets a reference to the top-level Configuration instance that represents the configuration hierarchy that the current ConfigurationElement instance belongs to.

(다음에서 상속됨 ConfigurationElement)
ElementInformation

ElementInformation 개체의 사용자 지정할 수 없는 정보와 기능을 포함하는 ConfigurationElement 개체를 가져옵니다.Gets an ElementInformation object that contains the non-customizable information and functionality of the ConfigurationElement object.

(다음에서 상속됨 ConfigurationElement)
ElementName

파생 클래스에서 재정의될 때 구성 파일에서 이 요소 컬렉션을 식별하는 데 사용되는 이름을 가져옵니다.Gets the name used to identify this collection of elements in the configuration file when overridden in a derived class.

ElementProperty

ConfigurationElementProperty 개체 자체를 나타내는 ConfigurationElement 개체를 가져옵니다.Gets the ConfigurationElementProperty object that represents the ConfigurationElement object itself.

(다음에서 상속됨 ConfigurationElement)
EmitClear

컬렉션이 지워졌는지 여부를 지정하는 값을 가져오거나 설정합니다.Gets or sets a value that specifies whether the collection has been cleared.

EvaluationContext

ContextInformation 개체의 ConfigurationElement 개체를 가져옵니다.Gets the ContextInformation object for the ConfigurationElement object.

(다음에서 상속됨 ConfigurationElement)
HasContext

CurrentConfiguration 속성이 null인지 여부를 나타내는 값을 가져옵니다.Gets a value that indicates whether the CurrentConfiguration property is null.

(다음에서 상속됨 ConfigurationElement)
IsSynchronized

컬렉션에 대한 액세스가 동기화되었는지 여부를 나타내는 값을 가져옵니다.Gets a value indicating whether access to the collection is synchronized.

Item[ConfigurationProperty]

이 구성 요소의 속성이나 특성을 가져오거나 설정합니다.Gets or sets a property or attribute of this configuration element.

(다음에서 상속됨 ConfigurationElement)
Item[String]

이 구성 요소의 속성, 특성 또는 자식 요소를 가져오거나 설정합니다.Gets or sets a property, attribute, or child element of this configuration element.

(다음에서 상속됨 ConfigurationElement)
LockAllAttributesExcept

잠긴 특성의 컬렉션을 가져옵니다.Gets the collection of locked attributes.

(다음에서 상속됨 ConfigurationElement)
LockAllElementsExcept

잠긴 요소의 컬렉션을 가져옵니다.Gets the collection of locked elements.

(다음에서 상속됨 ConfigurationElement)
LockAttributes

잠긴 특성의 컬렉션을 가져옵니다.Gets the collection of locked attributes.

(다음에서 상속됨 ConfigurationElement)
LockElements

잠긴 요소의 컬렉션을 가져옵니다.Gets the collection of locked elements.

(다음에서 상속됨 ConfigurationElement)
LockItem

요소가 잠겨 있는지 여부를 나타내는 값을 가져오거나 설정합니다.Gets or sets a value indicating whether the element is locked.

(다음에서 상속됨 ConfigurationElement)
Properties

속성 컬렉션을 가져옵니다.Gets the collection of properties.

(다음에서 상속됨 ConfigurationElement)
RemoveElementName

파생 클래스에서 재정의될 때 ConfigurationElement의 제거 작업과 연결할 ConfigurationElementCollection의 이름을 가져오거나 설정합니다.Gets or sets the name of the ConfigurationElement to associate with the remove operation in the ConfigurationElementCollection when overridden in a derived class.

SyncRoot

ConfigurationElementCollection에 대한 액세스를 동기화하는 데 사용되는 개체를 가져옵니다.Gets an object used to synchronize access to the ConfigurationElementCollection.

ThrowOnDuplicate

ConfigurationElement에 중복 ConfigurationElementCollection를 추가하려고 하면 예외가 throw되는지 여부를 나타내는 값을 가져옵니다.Gets a value indicating whether an attempt to add a duplicate ConfigurationElement to the ConfigurationElementCollection will cause an exception to be thrown.

메서드

BaseAdd(ConfigurationElement)

구성 요소를 ConfigurationElementCollection에 추가합니다.Adds a configuration element to the ConfigurationElementCollection.

BaseAdd(ConfigurationElement, Boolean)

구성 요소를 구성 요소 컬렉션에 추가합니다.Adds a configuration element to the configuration element collection.

BaseAdd(Int32, ConfigurationElement)

구성 요소를 구성 요소 컬렉션에 추가합니다.Adds a configuration element to the configuration element collection.

BaseClear()

컬렉션에서 구성 요소 개체를 모두 제거합니다.Removes all configuration element objects from the collection.

BaseGet(Int32)

지정된 인덱스 위치에 있는 구성 요소를 가져옵니다.Gets the configuration element at the specified index location.

BaseGet(Object)

지정된 키가 있는 구성 요소를 반환합니다.Returns the configuration element with the specified key.

BaseGetAllKeys()

ConfigurationElementCollection에 포함된 모든 구성 요소의 키 배열을 반환합니다.Returns an array of the keys for all of the configuration elements contained in the ConfigurationElementCollection.

BaseGetKey(Int32)

지정된 인덱스 위치에 있는 ConfigurationElement의 키를 가져옵니다.Gets the key for the ConfigurationElement at the specified index location.

BaseIndexOf(ConfigurationElement)

지정된 ConfigurationElement의 인덱스를 나타냅니다.Indicates the index of the specified ConfigurationElement.

BaseIsRemoved(Object)

지정된 키가 있는 ConfigurationElementConfigurationElementCollection에서 제거되었는지 여부를 나타냅니다.Indicates whether the ConfigurationElement with the specified key has been removed from the ConfigurationElementCollection.

BaseRemove(Object)

컬렉션에서 ConfigurationElement를 제거합니다.Removes a ConfigurationElement from the collection.

BaseRemoveAt(Int32)

지정된 인덱스 위치에서 ConfigurationElement를 제거합니다.Removes the ConfigurationElement at the specified index location.

CopyTo(ConfigurationElement[], Int32)

ConfigurationElementCollection의 내용을 배열에 복사합니다.Copies the contents of the ConfigurationElementCollection to an array.

CreateNewElement()

파생 클래스에서 재정의할 때 새 ConfigurationElement를 만듭니다.When overridden in a derived class, creates a new ConfigurationElement.

CreateNewElement(String)

파생 클래스에서 재정의될 때 새 ConfigurationElement를 만듭니다.Creates a new ConfigurationElement when overridden in a derived class.

DeserializeElement(XmlReader, Boolean)

구성 파일에서 XML을 읽습니다.Reads XML from the configuration file.

(다음에서 상속됨 ConfigurationElement)
Equals(Object)

ConfigurationElementCollection을 지정된 개체와 비교합니다.Compares the ConfigurationElementCollection to the specified object.

GetElementKey(ConfigurationElement)

파생 클래스에서 재정의될 때 지정된 구성 요소의 요소 키를 가져옵니다.Gets the element key for a specified configuration element when overridden in a derived class.

GetEnumerator()

IEnumerator을 반복하는 데 사용되는 ConfigurationElementCollection를 가져옵니다.Gets an IEnumerator which is used to iterate through the ConfigurationElementCollection.

GetHashCode()

ConfigurationElementCollection 인스턴스를 나타내는 고유 값을 가져옵니다.Gets a unique value representing the ConfigurationElementCollection instance.

GetTransformedAssemblyString(String)

지정된 어셈블리 이름의 변환된 버전을 반환합니다.Returns the transformed version of the specified assembly name.

(다음에서 상속됨 ConfigurationElement)
GetTransformedTypeString(String)

지정된 형식 이름의 변환된 버전을 반환합니다.Returns the transformed version of the specified type name.

(다음에서 상속됨 ConfigurationElement)
GetType()

현재 인스턴스의 Type을 가져옵니다.Gets the Type of the current instance.

(다음에서 상속됨 Object)
Init()

ConfigurationElement 개체를 초기 상태로 설정합니다.Sets the ConfigurationElement object to its initial state.

(다음에서 상속됨 ConfigurationElement)
InitializeDefault()

ConfigurationElement 개체 값의 기본 집합을 초기화하는 데 사용됩니다.Used to initialize a default set of values for the ConfigurationElement object.

(다음에서 상속됨 ConfigurationElement)
IsElementName(String)

지정된 ConfigurationElementConfigurationElementCollection에 있는지 여부를 나타냅니다.Indicates whether the specified ConfigurationElement exists in the ConfigurationElementCollection.

IsElementRemovable(ConfigurationElement)

지정한 ConfigurationElementConfigurationElementCollection에서 제거할 수 있는지 여부를 나타냅니다.Indicates whether the specified ConfigurationElement can be removed from the ConfigurationElementCollection.

IsModified()

파생 클래스에서 재정의될 때 이 ConfigurationElementCollection이 마지막으로 저장되거나 로드된 후 수정되었는지 여부를 나타냅니다.Indicates whether this ConfigurationElementCollection has been modified since it was last saved or loaded when overridden in a derived class.

IsReadOnly()

ConfigurationElementCollection 개체가 읽기 전용인지 여부를 나타냅니다.Indicates whether the ConfigurationElementCollection object is read only.

ListErrors(IList)

ConfigurationElement 개체와 모든 하위 요소의 잘못된 속성 오류를 전달된 목록에 추가합니다.Adds the invalid-property errors in this ConfigurationElement object, and in all subelements, to the passed list.

(다음에서 상속됨 ConfigurationElement)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.Creates a shallow copy of the current Object.

(다음에서 상속됨 Object)
OnDeserializeUnrecognizedAttribute(String, String)

deserialize하는 동안 알 수 없는 특성을 발견했는지 여부를 나타내는 값을 가져옵니다.Gets a value indicating whether an unknown attribute is encountered during deserialization.

(다음에서 상속됨 ConfigurationElement)
OnDeserializeUnrecognizedElement(String, XmlReader)

구성 시스템에서 예외를 throw하도록 합니다.Causes the configuration system to throw an exception.

OnRequiredPropertyNotFound(String)

필수 속성이 없으면 예외를 throw합니다.Throws an exception when a required property is not found.

(다음에서 상속됨 ConfigurationElement)
PostDeserialize()

deserialization 후에 호출됩니다.Called after deserialization.

(다음에서 상속됨 ConfigurationElement)
PreSerialize(XmlWriter)

serialization 전에 호출됩니다.Called before serialization.

(다음에서 상속됨 ConfigurationElement)
Reset(ConfigurationElement)

파생 클래스에서 재정의될 때 ConfigurationElementCollection을 수정되지 않은 상태로 다시 설정합니다.Resets the ConfigurationElementCollection to its unmodified state when overridden in a derived class.

ResetModified()

파생 클래스에서 재정의될 때 IsModified() 속성의 값을 false로 다시 설정합니다.Resets the value of the IsModified() property to false when overridden in a derived class.

SerializeElement(XmlWriter, Boolean)

파생 클래스에서 재정의될 때 구성 파일의 XML 요소에 구성 데이터를 씁니다.Writes the configuration data to an XML element in the configuration file when overridden in a derived class.

SerializeToXmlElement(XmlWriter, String)

파생 클래스에서 구현될 때 구성 요소의 외부 태그를 구성 파일에 씁니다.Writes the outer tags of this configuration element to the configuration file when implemented in a derived class.

(다음에서 상속됨 ConfigurationElement)
SetPropertyValue(ConfigurationProperty, Object, Boolean)

속성을 지정된 값으로 설정합니다.Sets a property to the specified value.

(다음에서 상속됨 ConfigurationElement)
SetReadOnly()

IsReadOnly() 개체와 모든 하위 요소에 대해 ConfigurationElementCollection 속성을 설정합니다.Sets the IsReadOnly() property for the ConfigurationElementCollection object and for all sub-elements.

ToString()

현재 개체를 나타내는 문자열을 반환합니다.Returns a string that represents the current object.

(다음에서 상속됨 Object)
Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode)

구성 계층 구조의 여러 수준에서 구성 정보를 병합한 결과를 되돌립니다.Reverses the effect of merging configuration information from different levels of the configuration hierarchy.

명시적 인터페이스 구현

ICollection.CopyTo(Array, Int32)

ConfigurationElementCollection을 배열에 복사합니다.Copies the ConfigurationElementCollection to an array.

확장 메서드

Cast<TResult>(IEnumerable)

IEnumerable의 요소를 지정된 형식으로 캐스팅합니다.Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

지정된 형식에 따라 IEnumerable의 요소를 필터링합니다.Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

쿼리를 병렬화할 수 있도록 합니다.Enables parallelization of a query.

AsQueryable(IEnumerable)

IEnumerableIQueryable로 변환합니다.Converts an IEnumerable to an IQueryable.

적용 대상

추가 정보