ConfigurationElementCollection ConfigurationElementCollection ConfigurationElementCollection ConfigurationElementCollection Class

定義

子要素のコレクションを格納する構成要素を表します。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
継承
ConfigurationElementCollectionConfigurationElementCollectionConfigurationElementCollectionConfigurationElementCollection
派生
実装

次の例は、使用する方法を示します、ConfigurationElementCollectionします。The following example shows how to use the ConfigurationElementCollection.

最初の例は、3 つのクラスで構成されています: UrlsSectionUrlsCollectionUrlConfigElementします。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 Microsoft.VisualBasic
Imports System
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

この 2 つ目のコード例では、前に指定されたクラスを使用します。This second code example uses the classes specified before. これら 2 つの例では、コンソール アプリケーション プロジェクトを組み合わせて使用します。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. 複雑なセクションは、1 つまたは複数の単純な要素、要素のコレクションおよびその他のセクションに含めることができます。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() ConfigurationElementCollection() ConfigurationElementCollection()

ConfigurationElementCollection クラスの新しいインスタンスを初期化します。Initializes a new instance of the ConfigurationElementCollection class.

ConfigurationElementCollection(IComparer) ConfigurationElementCollection(IComparer) ConfigurationElementCollection(IComparer) ConfigurationElementCollection(IComparer)

ConfigurationElementCollection クラスの新しいインスタンスを作成します。Creates a new instance of the ConfigurationElementCollection class.

プロパティ

AddElementName AddElementName AddElementName 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 ClearElementName ClearElementName 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 CollectionType CollectionType CollectionType

ConfigurationElementCollection の型を取得します。Gets the type of the ConfigurationElementCollection.

Count Count Count Count

コレクション内の要素の数を取得します。Gets the number of elements in the collection.

CurrentConfiguration CurrentConfiguration CurrentConfiguration CurrentConfiguration

現在の Configuration インスタンスが属している構成階層を表す最上位の ConfigurationElement インスタンスへの参照を取得します。Gets a reference to the top-level Configuration instance that represents the configuration hierarchy that the current ConfigurationElement instance belongs to.

(Inherited from ConfigurationElement)
ElementInformation ElementInformation ElementInformation ElementInformation

ElementInformation オブジェクトのカスタマイズできない情報と機能を格納する ConfigurationElement オブジェクトを取得します。Gets an ElementInformation object that contains the non-customizable information and functionality of the ConfigurationElement object.

(Inherited from ConfigurationElement)
ElementName ElementName ElementName ElementName

派生クラスでオーバーライドされると、構成ファイル内のこの要素のコレクションを識別するために使用する名前を取得します。Gets the name used to identify this collection of elements in the configuration file when overridden in a derived class.

ElementProperty ElementProperty ElementProperty ElementProperty

ConfigurationElementProperty オブジェクト自体を表す ConfigurationElement オブジェクトを取得します。Gets the ConfigurationElementProperty object that represents the ConfigurationElement object itself.

(Inherited from ConfigurationElement)
EmitClear EmitClear EmitClear EmitClear

コレクションが削除されたかどうかを示す値を取得または設定します。Gets or sets a value that specifies whether the collection has been cleared.

EvaluationContext EvaluationContext EvaluationContext EvaluationContext

ContextInformation オブジェクトの ConfigurationElement オブジェクトを取得します。Gets the ContextInformation object for the ConfigurationElement object.

(Inherited from ConfigurationElement)
HasContext HasContext HasContext HasContext

CurrentConfiguration プロパティが null であるかどうかを示す値を取得します。Gets a value that indicates whether the CurrentConfiguration property is null.

(Inherited from ConfigurationElement)
IsSynchronized IsSynchronized IsSynchronized IsSynchronized

コレクションへのアクセスの同期がとられているかどうかを示す値を取得します。Gets a value indicating whether access to the collection is synchronized.

Item[ConfigurationProperty] Item[ConfigurationProperty] Item[ConfigurationProperty] Item[ConfigurationProperty]

この構成要素のプロパティまたは属性を取得または設定します。Gets or sets a property or attribute of this configuration element.

(Inherited from ConfigurationElement)
Item[String] Item[String] Item[String] Item[String]

この構成要素のプロパティ、属性、または子要素を取得または設定します。Gets or sets a property, attribute, or child element of this configuration element.

(Inherited from ConfigurationElement)
LockAllAttributesExcept LockAllAttributesExcept LockAllAttributesExcept LockAllAttributesExcept

ロックされている属性のコレクションを取得します。Gets the collection of locked attributes.

(Inherited from ConfigurationElement)
LockAllElementsExcept LockAllElementsExcept LockAllElementsExcept LockAllElementsExcept

ロックされている要素のコレクションを取得します。Gets the collection of locked elements.

(Inherited from ConfigurationElement)
LockAttributes LockAttributes LockAttributes LockAttributes

ロックされている属性のコレクションを取得します。Gets the collection of locked attributes

(Inherited from ConfigurationElement)
LockElements LockElements LockElements LockElements

ロックされている要素のコレクションを取得します。Gets the collection of locked elements.

(Inherited from ConfigurationElement)
LockItem LockItem LockItem LockItem

要素がロックされているかどうかを示す値を取得または設定します。Gets or sets a value indicating whether the element is locked.

(Inherited from ConfigurationElement)
Properties Properties Properties Properties

プロパティのコレクションを取得します。Gets the collection of properties.

(Inherited from ConfigurationElement)
RemoveElementName RemoveElementName RemoveElementName 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 SyncRoot SyncRoot SyncRoot

ConfigurationElementCollection へのアクセスを同期するために使用するオブジェクトを取得します。Gets an object used to synchronize access to the ConfigurationElementCollection.

ThrowOnDuplicate ThrowOnDuplicate ThrowOnDuplicate ThrowOnDuplicate

重複する ConfigurationElementConfigurationElementCollection に追加しようとしたときに、例外をスローするかどうかを示す値を取得します。Gets a value indicating whether an attempt to add a duplicate ConfigurationElement to the ConfigurationElementCollection will cause an exception to be thrown.

メソッド

BaseAdd(ConfigurationElement) BaseAdd(ConfigurationElement) BaseAdd(ConfigurationElement) BaseAdd(ConfigurationElement)

ConfigurationElementCollection に構成要素を追加します。Adds a configuration element to the ConfigurationElementCollection.

BaseAdd(ConfigurationElement, Boolean) BaseAdd(ConfigurationElement, Boolean) BaseAdd(ConfigurationElement, Boolean) BaseAdd(ConfigurationElement, Boolean)

構成要素のコレクションに構成要素を追加します。Adds a configuration element to the configuration element collection.

BaseAdd(Int32, ConfigurationElement) BaseAdd(Int32, ConfigurationElement) BaseAdd(Int32, ConfigurationElement) BaseAdd(Int32, ConfigurationElement)

構成要素のコレクションに構成要素を追加します。Adds a configuration element to the configuration element collection.

BaseClear() BaseClear() BaseClear() BaseClear()

コレクションからすべての構成要素オブジェクトを削除します。Removes all configuration element objects from the collection.

BaseGet(Int32) BaseGet(Int32) BaseGet(Int32) BaseGet(Int32)

指定したインデックス位置にある構成要素を取得します。Gets the configuration element at the specified index location.

BaseGet(Object) BaseGet(Object) BaseGet(Object) BaseGet(Object)

指定したキーを持つ構成要素を返します。Returns the configuration element with the specified key.

BaseGetAllKeys() BaseGetAllKeys() BaseGetAllKeys() BaseGetAllKeys()

ConfigurationElementCollection に格納されているすべての構成要素のキーの配列を返します。Returns an array of the keys for all of the configuration elements contained in the ConfigurationElementCollection.

BaseGetKey(Int32) BaseGetKey(Int32) BaseGetKey(Int32) BaseGetKey(Int32)

指定したインデックス位置にある ConfigurationElement のキーを取得します。Gets the key for the ConfigurationElement at the specified index location.

BaseIndexOf(ConfigurationElement) BaseIndexOf(ConfigurationElement) BaseIndexOf(ConfigurationElement) BaseIndexOf(ConfigurationElement)

指定した ConfigurationElement のインデックスを示します。Indicates the index of the specified ConfigurationElement.

BaseIsRemoved(Object) BaseIsRemoved(Object) BaseIsRemoved(Object) BaseIsRemoved(Object)

指定したキーを持つ ConfigurationElementConfigurationElementCollection から削除されているかどうかを示します。Indicates whether the ConfigurationElement with the specified key has been removed from the ConfigurationElementCollection.

BaseRemove(Object) BaseRemove(Object) BaseRemove(Object) BaseRemove(Object)

ConfigurationElement をコレクションから削除します。Removes a ConfigurationElement from the collection.

BaseRemoveAt(Int32) BaseRemoveAt(Int32) BaseRemoveAt(Int32) BaseRemoveAt(Int32)

指定したインデックス位置にある ConfigurationElement を削除します。Removes the ConfigurationElement at the specified index location.

CopyTo(ConfigurationElement[], Int32) CopyTo(ConfigurationElement[], Int32) CopyTo(ConfigurationElement[], Int32) CopyTo(ConfigurationElement[], Int32)

ConfigurationElementCollection の内容を配列にコピーします。Copies the contents of the ConfigurationElementCollection to an array.

CreateNewElement() CreateNewElement() CreateNewElement() CreateNewElement()

派生クラスでオーバーライドされると、新しい ConfigurationElement を作成します。When overridden in a derived class, creates a new ConfigurationElement.

CreateNewElement(String) CreateNewElement(String) CreateNewElement(String) CreateNewElement(String)

派生クラスでオーバーライドされると、新しい ConfigurationElement を作成します。Creates a new ConfigurationElement when overridden in a derived class.

DeserializeElement(XmlReader, Boolean) DeserializeElement(XmlReader, Boolean) DeserializeElement(XmlReader, Boolean) DeserializeElement(XmlReader, Boolean)

構成ファイルから XML を読み取ります。Reads XML from the configuration file.

(Inherited from ConfigurationElement)
Equals(Object) Equals(Object) Equals(Object) Equals(Object)

ConfigurationElementCollection と指定したオブジェクトを比較します。Compares the ConfigurationElementCollection to the specified object.

GetElementKey(ConfigurationElement) GetElementKey(ConfigurationElement) GetElementKey(ConfigurationElement) GetElementKey(ConfigurationElement)

派生クラスでオーバーライドされると、指定した構成要素の要素キーを取得します。Gets the element key for a specified configuration element when overridden in a derived class.

GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

IEnumerator の反復処理に使用する ConfigurationElementCollection を取得します。Gets an IEnumerator which is used to iterate through the ConfigurationElementCollection.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

ConfigurationElementCollection インスタンスを表す一意の値を取得します。Gets a unique value representing the ConfigurationElementCollection instance.

GetTransformedAssemblyString(String) GetTransformedAssemblyString(String) GetTransformedAssemblyString(String) GetTransformedAssemblyString(String)

指定されたアセンブリ名を変換して返します。Returns the transformed version of the specified assembly name.

(Inherited from ConfigurationElement)
GetTransformedTypeString(String) GetTransformedTypeString(String) GetTransformedTypeString(String) GetTransformedTypeString(String)

指定された型名を変換して返します。Returns the transformed version of the specified type name.

(Inherited from ConfigurationElement)
GetType() GetType() GetType() GetType()

現在のインスタンスの Type を取得します。Gets the Type of the current instance.

(Inherited from Object)
Init() Init() Init() Init()

ConfigurationElement オブジェクトを初期状態に設定します。Sets the ConfigurationElement object to its initial state.

(Inherited from ConfigurationElement)
InitializeDefault() InitializeDefault() InitializeDefault() InitializeDefault()

ConfigurationElement オブジェクトの既定の値セットを初期化するために使用します。Used to initialize a default set of values for the ConfigurationElement object.

(Inherited from ConfigurationElement)
IsElementName(String) IsElementName(String) IsElementName(String) IsElementName(String)

指定した ConfigurationElementConfigurationElementCollection に存在するかどうかを示します。Indicates whether the specified ConfigurationElement exists in the ConfigurationElementCollection.

IsElementRemovable(ConfigurationElement) IsElementRemovable(ConfigurationElement) IsElementRemovable(ConfigurationElement) IsElementRemovable(ConfigurationElement)

指定した ConfigurationElementConfigurationElementCollection から削除できるかどうかを示します。Indicates whether the specified ConfigurationElement can be removed from the ConfigurationElementCollection.

IsModified() IsModified() IsModified() IsModified()

派生クラスでオーバーライドされると、この ConfigurationElementCollection が最後に保存された後または読み込まれた後に、変更されているかどうかを示します。Indicates whether this ConfigurationElementCollection has been modified since it was last saved or loaded when overridden in a derived class.

IsReadOnly() IsReadOnly() IsReadOnly() IsReadOnly()

ConfigurationElementCollection オブジェクトが読み取り専用かどうかを示します。Indicates whether the ConfigurationElementCollection object is read only.

ListErrors(IList) ListErrors(IList) ListErrors(IList) ListErrors(IList)

この ConfigurationElement オブジェクトおよびすべてのサブ要素の無効なプロパティのエラーを、渡されたリストに追加します。Adds the invalid-property errors in this ConfigurationElement object, and in all subelements, to the passed list.

(Inherited from ConfigurationElement)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

現在の Object の簡易コピーを作成します。Creates a shallow copy of the current Object.

(Inherited from Object)
OnDeserializeUnrecognizedAttribute(String, String) OnDeserializeUnrecognizedAttribute(String, String) OnDeserializeUnrecognizedAttribute(String, String) OnDeserializeUnrecognizedAttribute(String, String)

逆シリカル化中に不明な属性が発生したかどうかを示す値を取得します。Gets a value indicating whether an unknown attribute is encountered during deserialization.

(Inherited from ConfigurationElement)
OnDeserializeUnrecognizedElement(String, XmlReader) OnDeserializeUnrecognizedElement(String, XmlReader) OnDeserializeUnrecognizedElement(String, XmlReader) OnDeserializeUnrecognizedElement(String, XmlReader)

構成システムが例外をスローするようにします。Causes the configuration system to throw an exception.

OnRequiredPropertyNotFound(String) OnRequiredPropertyNotFound(String) OnRequiredPropertyNotFound(String) OnRequiredPropertyNotFound(String)

必要なプロパティが見つからないと例外がスローされます。Throws an exception when a required property is not found.

(Inherited from ConfigurationElement)
PostDeserialize() PostDeserialize() PostDeserialize() PostDeserialize()

逆シリアル化後に呼び出されます。Called after deserialization.

(Inherited from ConfigurationElement)
PreSerialize(XmlWriter) PreSerialize(XmlWriter) PreSerialize(XmlWriter) PreSerialize(XmlWriter)

シリアル化前に呼び出されます。Called before serialization.

(Inherited from ConfigurationElement)
Reset(ConfigurationElement) Reset(ConfigurationElement) Reset(ConfigurationElement) Reset(ConfigurationElement)

派生クラスでオーバーライドされると、ConfigurationElementCollection を変更されていない状態にリセットします。Resets the ConfigurationElementCollection to its unmodified state when overridden in a derived class.

ResetModified() ResetModified() ResetModified() ResetModified()

派生クラスでオーバーライドされると、IsModified() プロパティの値を false にリセットします。Resets the value of the IsModified() property to false when overridden in a derived class.

SerializeElement(XmlWriter, Boolean) SerializeElement(XmlWriter, Boolean) SerializeElement(XmlWriter, Boolean) 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) SerializeToXmlElement(XmlWriter, String) SerializeToXmlElement(XmlWriter, String) SerializeToXmlElement(XmlWriter, String)

派生クラスに実装されている場合、この構成要素の外側のタグを構成ファイルに書き込みます。Writes the outer tags of this configuration element to the configuration file when implemented in a derived class.

(Inherited from ConfigurationElement)
SetPropertyValue(ConfigurationProperty, Object, Boolean) SetPropertyValue(ConfigurationProperty, Object, Boolean) SetPropertyValue(ConfigurationProperty, Object, Boolean) SetPropertyValue(ConfigurationProperty, Object, Boolean)

プロパティを指定した値に設定します。Sets a property to the specified value.

(Inherited from ConfigurationElement)
SetReadOnly() SetReadOnly() SetReadOnly() SetReadOnly()

IsReadOnly() オブジェクトとすべてのサブ要素の ConfigurationElementCollection プロパティを設定します。Sets the IsReadOnly() property for the ConfigurationElementCollection object and for all sub-elements.

ToString() ToString() ToString() ToString()

現在のオブジェクトを表す文字列を返します。Returns a string that represents the current object.

(Inherited from Object)
Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode) Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode) Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode) Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode)

構成階層の異なるレベルの構成情報をマージした効果を元に戻します。Reverses the effect of merging configuration information from different levels of the configuration hierarchy.

明示的なインターフェイスの実装

ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32)

ConfigurationElementCollection を配列にコピーします。Copies the ConfigurationElementCollection to an array.

拡張メソッド

Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable)

IEnumerable の要素を、指定した型にキャストします。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable)

指定された型に基づいて IEnumerable の要素をフィルター処理します。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable)

クエリの並列化を有効にします。Enables parallelization of a query.

AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable)

変換、IEnumerableIQueryableします。Converts an IEnumerable to an IQueryable.

適用対象

こちらもご覧ください