Unrecognized item "Element" in the configuration file with a custom configuration section

I have a custom configuration based on some classes. My problem is that I am getting an error stating that the configuration item is not recognized. The class is as follows:

[ConfigurationCollection(typeof(SectionItem), AddItemName = "Item", CollectionType = ConfigurationElementCollectionType.BasicMap)] public class Sections : ConfigurationElementCollection { public SectionItem this[int index] { get { return BaseGet(index) as SectionItem; } set { if (BaseGet(index) != null) { BaseRemoveAt(index); } BaseAdd(index, value); } } public new SectionItem this[string response] { get { return (SectionItem)BaseGet(response); } set { if (BaseGet(response) != null) { BaseRemoveAt(BaseIndexOf(BaseGet(response))); } BaseAdd(value); } } protected override ConfigurationElement CreateNewElement() { return new SectionItem(); } protected override object GetElementKey(ConfigurationElement element) { return ((SectionItem)element).Key; } } 

And the SectionItem class:

 public class SectionItem : ConfigurationElement { [ConfigurationProperty("key", IsRequired = true, IsKey = true)] public string Key { get { return this["key"] as string; } } } 

If I add a configuration property of type SectionItems to the Sections class, which will not work for me, because I want to have several SectonItems inside the Section tag in the configuration file. I was looking for solutions, but everything I found did not work with this. To better understand what I'm trying to achieve, this is what my configuration looks like:

 <configuration> <configSections> <section name="AdminConfig" type="XmlTest.AdminConfig, XmlTest"/> </configSections> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <AdminConfig> <Field name="field1" key="12345" path="asd"/> <Section> <Item key="12345"/> <Item key="54321"/> </Section> </AdminConfig> </configuration> 
+7
c # configuration
source share
1 answer

OK, so I found the problem. Although the Sections class had this [ConfigurationCollection(typeof(SectionItem), AddItemName = "Item", CollectionType = ConfigurationElementCollectionType.BasicMap)] , I had to annotate the property in the ConfigurationSection class as follows:

  [ConfigurationProperty("Section")] [ConfigurationCollection(typeof(Sections), AddItemName = "Item")] public Sections Sections { get { return (Sections)this["Section"]; } } 

Now the elements are recognized, and the material works correctly.

+9
source share

All Articles