ConfigurationElementCollection Class
TOC
Collapse the table of content
Expand the table of content

ConfigurationElementCollection Class

 

Represents a configuration element containing a collection of child elements.

Namespace:   System.Configuration
Assembly:  System.Configuration (in System.Configuration.dll)

System.Object
  System.Configuration.ConfigurationElement
    System.Configuration.ConfigurationElementCollection
      System.Configuration.ConnectionStringSettingsCollection
      System.Configuration.KeyValueConfigurationCollection
      System.Configuration.NameValueConfigurationCollection
      System.Configuration.ProviderSettingsCollection
      System.Configuration.SchemeSettingElementCollection
      System.Configuration.SettingElementCollection
      System.IdentityModel.Configuration.AudienceUriElementCollection
      System.IdentityModel.Configuration.IdentityConfigurationElementCollection
      System.IdentityModel.Configuration.SecurityTokenHandlerElementCollection
      System.IdentityModel.Configuration.SecurityTokenHandlerSetElementCollection
      System.IdentityModel.Services.Configuration.FederationConfigurationElementCollection
      System.Net.Configuration.AuthenticationModuleElementCollection
      System.Net.Configuration.BypassElementCollection
      System.Net.Configuration.ConnectionManagementElementCollection
      System.Net.Configuration.WebRequestModuleElementCollection
      System.Runtime.Caching.Configuration.MemoryCacheSettingsCollection
      System.Runtime.Serialization.Configuration.DeclaredTypeElementCollection
      System.Runtime.Serialization.Configuration.ParameterElementCollection
      System.Runtime.Serialization.Configuration.TypeElementCollection
      System.Security.Authentication.ExtendedProtection.Configuration.ServiceNameElementCollection
      System.ServiceModel.Activities.Tracking.Configuration.TrackingConfigurationCollection<TConfigurationElement>
      System.ServiceModel.Configuration.ServiceModelConfigurationElementCollection<ConfigurationElementType>
      System.ServiceModel.Routing.Configuration.BackupEndpointCollection
      System.ServiceModel.Routing.Configuration.BackupListCollection
      System.ServiceModel.Routing.Configuration.FilterElementCollection
      System.ServiceModel.Routing.Configuration.FilterTableCollection
      System.ServiceModel.Routing.Configuration.FilterTableEntryCollection
      System.ServiceModel.Routing.Configuration.NamespaceElementCollection
      System.Web.Configuration.AssemblyCollection
      System.Web.Configuration.AuthorizationRuleCollection
      System.Web.Configuration.BufferModesCollection
      System.Web.Configuration.BuildProviderCollection
      System.Web.Configuration.ClientTargetCollection
      System.Web.Configuration.CodeSubDirectoriesCollection
      System.Web.Configuration.CompilerCollection
      System.Web.Configuration.ConvertersCollection
      System.Web.Configuration.CustomErrorCollection
      System.Web.Configuration.EventMappingSettingsCollection
      System.Web.Configuration.ExpressionBuilderCollection
      System.Web.Configuration.FolderLevelBuildProviderCollection
      System.Web.Configuration.FormsAuthenticationUserCollection
      System.Web.Configuration.FullTrustAssemblyCollection
      System.Web.Configuration.HttpHandlerActionCollection
      System.Web.Configuration.HttpModuleActionCollection
      System.Web.Configuration.IgnoreDeviceFilterElementCollection
      System.Web.Configuration.NamespaceCollection
      System.Web.Configuration.OutputCacheProfileCollection
      System.Web.Configuration.PartialTrustVisibleAssemblyCollection
      System.Web.Configuration.ProfileGroupSettingsCollection
      System.Web.Configuration.ProfilePropertySettingsCollection
      System.Web.Configuration.ProfileSettingsCollection
      System.Web.Configuration.ProtocolCollection
      System.Web.Configuration.RuleSettingsCollection
      System.Web.Configuration.SqlCacheDependencyDatabaseCollection
      System.Web.Configuration.TagMapCollection
      System.Web.Configuration.TagPrefixCollection
      System.Web.Configuration.TransformerInfoCollection
      System.Web.Configuration.TrustLevelCollection
      System.Web.Configuration.UrlMappingCollection
      System.Web.Mobile.DeviceFilterElementCollection
      System.Web.Services.Configuration.ProtocolElementCollection
      System.Web.Services.Configuration.SoapExtensionTypeElementCollection
      System.Web.Services.Configuration.TypeElementCollection
      System.Web.Services.Configuration.WsiProfilesElementCollection
      System.Web.UI.MobileControls.ControlElementCollection
      System.Web.UI.MobileControls.DeviceElementCollection
      System.Workflow.Runtime.Configuration.WorkflowRuntimeServiceElementCollection
      System.Xml.Serialization.Configuration.SchemaImporterExtensionElementCollection

public abstract class ConfigurationElementCollection : ConfigurationElement, 
	ICollection, IEnumerable

NameDescription
System_CAPS_protmethodConfigurationElementCollection()

Initializes a new instance of the ConfigurationElementCollection class.

System_CAPS_protmethodConfigurationElementCollection(IComparer)

Creates a new instance of the ConfigurationElementCollection class.

NameDescription
System_CAPS_protpropertyAddElementName

Gets or sets the name of the ConfigurationElement to associate with the add operation in the ConfigurationElementCollection when overridden in a derived class.

System_CAPS_protpropertyClearElementName

Gets or sets the name for the ConfigurationElement to associate with the clear operation in the ConfigurationElementCollection when overridden in a derived class.

System_CAPS_pubpropertyCollectionType

Gets the type of the ConfigurationElementCollection.

System_CAPS_pubpropertyCount

Gets the number of elements in the collection.

System_CAPS_pubpropertyCurrentConfiguration

Gets a reference to the top-level Configuration instance that represents the configuration hierarchy that the current ConfigurationElement instance belongs to.(Inherited from ConfigurationElement.)

System_CAPS_pubpropertyElementInformation

Gets an ElementInformation object that contains the non-customizable information and functionality of the ConfigurationElement object. (Inherited from ConfigurationElement.)

System_CAPS_protpropertyElementName

Gets the name used to identify this collection of elements in the configuration file when overridden in a derived class.

System_CAPS_protpropertyElementProperty

Gets the ConfigurationElementProperty object that represents the ConfigurationElement object itself.(Inherited from ConfigurationElement.)

System_CAPS_pubpropertyEmitClear

Gets or sets a value that specifies whether the collection has been cleared.

System_CAPS_protpropertyEvaluationContext

Gets the ContextInformation object for the ConfigurationElement object.(Inherited from ConfigurationElement.)

System_CAPS_protpropertyHasContext

(Inherited from ConfigurationElement.)

System_CAPS_pubpropertyIsSynchronized

Gets a value indicating whether access to the collection is synchronized.

System_CAPS_protpropertyItem[ConfigurationProperty]

Gets or sets a property or attribute of this configuration element.(Inherited from ConfigurationElement.)

System_CAPS_protpropertyItem[String]

Gets or sets a property, attribute, or child element of this configuration element.(Inherited from ConfigurationElement.)

System_CAPS_pubpropertyLockAllAttributesExcept

Gets the collection of locked attributes.(Inherited from ConfigurationElement.)

System_CAPS_pubpropertyLockAllElementsExcept

Gets the collection of locked elements.(Inherited from ConfigurationElement.)

System_CAPS_pubpropertyLockAttributes

Gets the collection of locked attributes (Inherited from ConfigurationElement.)

System_CAPS_pubpropertyLockElements

Gets the collection of locked elements.(Inherited from ConfigurationElement.)

System_CAPS_pubpropertyLockItem

Gets or sets a value indicating whether the element is locked.(Inherited from ConfigurationElement.)

System_CAPS_protpropertyProperties

Gets the collection of properties.(Inherited from ConfigurationElement.)

System_CAPS_protpropertyRemoveElementName

Gets or sets the name of the ConfigurationElement to associate with the remove operation in the ConfigurationElementCollection when overridden in a derived class.

System_CAPS_pubpropertySyncRoot

Gets an object used to synchronize access to the ConfigurationElementCollection.

System_CAPS_protpropertyThrowOnDuplicate

Gets a value indicating whether an attempt to add a duplicate ConfigurationElement to the ConfigurationElementCollection will cause an exception to be thrown.

NameDescription
System_CAPS_protmethodBaseAdd(ConfigurationElement)

Adds a configuration element to the ConfigurationElementCollection.

System_CAPS_protmethodBaseAdd(ConfigurationElement, Boolean)

Adds a configuration element to the configuration element collection.

System_CAPS_protmethodBaseAdd(Int32, ConfigurationElement)

Adds a configuration element to the configuration element collection.

System_CAPS_protmethodBaseClear()

Removes all configuration element objects from the collection.

System_CAPS_protmethodBaseGet(Int32)

Gets the configuration element at the specified index location.

System_CAPS_protmethodBaseGet(Object)

Returns the configuration element with the specified key.

System_CAPS_protmethodBaseGetAllKeys()

Returns an array of the keys for all of the configuration elements contained in the ConfigurationElementCollection.

System_CAPS_protmethodBaseGetKey(Int32)

Gets the key for the ConfigurationElement at the specified index location.

System_CAPS_protmethodBaseIndexOf(ConfigurationElement)

Indicates the index of the specified ConfigurationElement.

System_CAPS_protmethodBaseIsRemoved(Object)

Indicates whether the ConfigurationElement with the specified key has been removed from the ConfigurationElementCollection.

System_CAPS_protmethodBaseRemove(Object)

Removes a ConfigurationElement from the collection.

System_CAPS_protmethodBaseRemoveAt(Int32)

Removes the ConfigurationElement at the specified index location.

System_CAPS_pubmethodCopyTo(ConfigurationElement[], Int32)

Copies the contents of the ConfigurationElementCollection to an array.

System_CAPS_protmethodCreateNewElement()

When overridden in a derived class, creates a new ConfigurationElement.

System_CAPS_protmethodCreateNewElement(String)

Creates a new ConfigurationElement when overridden in a derived class.

System_CAPS_protmethodDeserializeElement(XmlReader, Boolean)

Reads XML from the configuration file.(Inherited from ConfigurationElement.)

System_CAPS_pubmethodEquals(Object)

Compares the ConfigurationElementCollection to the specified object.(Overrides ConfigurationElement.Equals(Object).)

System_CAPS_protmethodFinalize()

Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.(Inherited from Object.)

System_CAPS_protmethodGetElementKey(ConfigurationElement)

Gets the element key for a specified configuration element when overridden in a derived class.

System_CAPS_pubmethodGetEnumerator()

This API supports the product infrastructure and is not intended to be used directly from your code. Gets an IEnumerator which is used to iterate through the ConfigurationElementCollection.

System_CAPS_pubmethodGetHashCode()

Gets a unique value representing the ConfigurationElementCollection instance.(Overrides ConfigurationElement.GetHashCode().)

System_CAPS_protmethodGetTransformedAssemblyString(String)

Returns the transformed version of the specified assembly name. (Inherited from ConfigurationElement.)

System_CAPS_protmethodGetTransformedTypeString(String)

Returns the transformed version of the specified type name.(Inherited from ConfigurationElement.)

System_CAPS_pubmethodGetType()

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_protmethodInit()

Sets the ConfigurationElement object to its initial state.(Inherited from ConfigurationElement.)

System_CAPS_protmethodInitializeDefault()

Used to initialize a default set of values for the ConfigurationElement object.(Inherited from ConfigurationElement.)

System_CAPS_protmethodIsElementName(String)

Indicates whether the specified ConfigurationElement exists in the ConfigurationElementCollection.

System_CAPS_protmethodIsElementRemovable(ConfigurationElement)

Indicates whether the specified ConfigurationElement can be removed from the ConfigurationElementCollection.

System_CAPS_protmethodIsModified()

Indicates whether this ConfigurationElementCollection has been modified since it was last saved or loaded when overridden in a derived class.(Overrides ConfigurationElement.IsModified().)

System_CAPS_pubmethodIsReadOnly()

Indicates whether the ConfigurationElementCollection object is read only.(Overrides ConfigurationElement.IsReadOnly().)

System_CAPS_protmethodListErrors(IList)

Adds the invalid-property errors in this ConfigurationElement object, and in all subelements, to the passed list.(Inherited from ConfigurationElement.)

System_CAPS_protmethodMemberwiseClone()

Creates a shallow copy of the current Object.(Inherited from Object.)

System_CAPS_protmethodOnDeserializeUnrecognizedAttribute(String, String)

Gets a value indicating whether an unknown attribute is encountered during deserialization.(Inherited from ConfigurationElement.)

System_CAPS_protmethodOnDeserializeUnrecognizedElement(String, XmlReader)

Causes the configuration system to throw an exception.(Overrides ConfigurationElement.OnDeserializeUnrecognizedElement(String, XmlReader).)

System_CAPS_protmethodOnRequiredPropertyNotFound(String)

Throws an exception when a required property is not found.(Inherited from ConfigurationElement.)

System_CAPS_protmethodPostDeserialize()

Called after deserialization.(Inherited from ConfigurationElement.)

System_CAPS_protmethodPreSerialize(XmlWriter)

Called before serialization.(Inherited from ConfigurationElement.)

System_CAPS_protmethodReset(ConfigurationElement)

Resets the ConfigurationElementCollection to its unmodified state when overridden in a derived class.(Overrides ConfigurationElement.Reset(ConfigurationElement).)

System_CAPS_protmethodResetModified()

Resets the value of the IsModified property to false when overridden in a derived class.(Overrides ConfigurationElement.ResetModified().)

System_CAPS_protmethodSerializeElement(XmlWriter, Boolean)

Writes the configuration data to an XML element in the configuration file when overridden in a derived class.(Overrides ConfigurationElement.SerializeElement(XmlWriter, Boolean).)

System_CAPS_protmethodSerializeToXmlElement(XmlWriter, String)

Writes the outer tags of this configuration element to the configuration file when implemented in a derived class.(Inherited from ConfigurationElement.)

System_CAPS_protmethodSetPropertyValue(ConfigurationProperty, Object, Boolean)

Sets a property to the specified value.(Inherited from ConfigurationElement.)

System_CAPS_protmethodSetReadOnly()

This API supports the product infrastructure and is not intended to be used directly from your code. Sets the IsReadOnly property for the ConfigurationElementCollection object and for all sub-elements.(Overrides ConfigurationElement.SetReadOnly().)

System_CAPS_pubmethodToString()

Returns a string that represents the current object.(Inherited from Object.)

System_CAPS_protmethodUnmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode)

This API supports the product infrastructure and is not intended to be used directly from your code. Reverses the effect of merging configuration information from different levels of the configuration hierarchy (Overrides ConfigurationElement.Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode).)

NameDescription
System_CAPS_pubinterfaceSystem_CAPS_privmethodICollection.CopyTo(Array, Int32)

Copies the ConfigurationElementCollection to an array.

NameDescription
System_CAPS_pubmethodAsParallel()

Overloaded. Enables parallelization of a query.(Defined by ParallelEnumerable.)

System_CAPS_pubmethodAsQueryable()

Overloaded. Converts an IEnumerable to an IQueryable.(Defined by Queryable.)

System_CAPS_pubmethodCast<TResult>()

Casts the elements of an IEnumerable to the specified type.(Defined by Enumerable.)

System_CAPS_pubmethodOfType<TResult>()

Filters the elements of an IEnumerable based on a specified type.(Defined by Enumerable.)

The ConfigurationElementCollection represents a collection of elements within a configuration file.

System_CAPS_noteNote

An element within a configuration file refers to a basic XML element or a section. 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.

You use the ConfigurationElementCollection to work with a collection of ConfigurationElement objects. Implement this class to add collections of custom ConfigurationElement elements to a ConfigurationSection.

Notes to Implementers:

You can use a programmatic or a declarative (attributed) coding model to create a custom configuration element.

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. These attributes instruct the ASP.NET configuration system about the property types and their default values. ASP.NET can use reflection to obtain this information and then create the element property objects and perform the required initialization.

The following example shows how to use the ConfigurationElementCollection.

The first example consists of three classes: UrlsSection, UrlsCollection and UrlConfigElement.The UrlsSection class uses the ConfigurationCollectionAttribute to define a custom configuration section. 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;
        }
    }

}

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 (selection != string.Empty)
                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();
        }
    }
}

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

.NET Framework
Available since 2.0

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Return to top
Show:
© 2016 Microsoft