How to create a configuration section containing a collection

Here is a big question and answer that illustrates how to create a custom configuration section that is able to analyze the configuration of the following form into .Net objects:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="CustomConfigSection" type="ConfigTest.CustomConfigSection,ConfigTest" />
  </configSections>

  <CustomConfigSection>
    <ConfigElements>
      <ConfigElement key="Test1" />
      <ConfigElement key="Test2" />
    </ConfigElements>
  </CustomConfigSection>

</configuration>

My question is: does anyone know how to create the same custom configuration section without an element ConfigElements? For example, one that will parse the following element CustomConfigSectioninstead of the above:

  <CustomConfigSection>
    <ConfigElement key="Test1" />
    <ConfigElement key="Test2" />
  </CustomConfigSection>

, , CustomConfigSection ConfigurationSection ConfigurationElementCollection, , , #. , , , IConfigurationSectionHandler, .Net v2. - , ? .

+4
1

ConfigurationSection, ConfigurationElementCollection. :

public class CustomConfigSection : ConfigurationSection
{
    [ConfigurationProperty("", IsDefaultCollection = true)]
    public MyConfigElementCollection ConfigElementCollection
    {
        get
        {
            return (MyConfigElementCollection)base[""];
        }
    }
}

:

[ConfigurationCollection(typeof(MyConfigElement), AddItemName = "ConfigElement"]
public class MyConfigElementCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new MyConfigElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        if (element == null)
            throw new ArgumentNullException("element");

        return ((MyConfigElement)element).key;
    }
}

:

public class MyConfigElement: ConfigurationElement
{
    [ConfigurationProperty("key", IsRequired = true, IsKey = true)]
    public string Key
    {
        get
        {
            return (string)base["key"];
        }
    }   
}
+9

All Articles