I have a .config file, where i need to add new ConfigurationElement under the ConfigurationElementCollection, I have followed the documentation of microsoft and implemented everything https://learn.microsoft.com/en-us/dotnet/api/system.configuration.configurationelementcollection?view=windowsdesktop-7.0.
But BaseAdd override method always throws the read-only exception.
This is my config file data, i am trying to add new element under testelements attribute.
<testElements>
<testElements>
<clear/>
<add name="test"
model = "model"/>
This is ConfigurationElement Class:
public class TestElements: ConfigurationElement
{
public TestElements()
{
}
public TestElements(string elementName)
{
Name = elementName;
}
[ConfigurationProperty("name",
IsRequired = true, IsKey = true)]
public string Name
{
get
{
return ((string)this["name"]);
}
set
{
this["name"] = value;
}
}
[ConfigurationProperty("model", IsRequired = true, IsKey = true)]
public string ModelName
{
get
{
return (string)this["model"];
}
set
{
this["model"] = value;
}
}
}
My configurationelementCollection class:
public class TestElementsCollection : ConfigurationElementCollection
{
public TestElementsCollection()
{
}
public override
ConfigurationElementCollectionType CollectionType
{
get
{
return
ConfigurationElementCollectionType.AddRemoveClearMap;
}
}
protected override
ConfigurationElement CreateNewElement()
{
return new ServiceRouteDefaults();
}
protected override
ConfigurationElement CreateNewElement(
string elementName)
{
return new TestElements(elementName);
}
public new string AddElementName
{
get
{ return base.AddElementName; }
set
{ base.AddElementName = value; }
}
public new string ClearElementName
{
get
{ return base.ClearElementName; }
set
{ base.ClearElementName = value; }
}
public new string RemoveElementName
{
get
{ return base.RemoveElementName; }
}
public void Add(TestElements url)
{
BaseAdd(url);
// Add custom code here.
}
protected override void
BaseAdd(ConfigurationElement element)
{
BaseAdd(element, false);
// Add custom code here.
}
public void Remove(TestElements url)
{
string key = GetElementKey(url).ToString();
if (BaseIndexOf(url) >= 0)
BaseRemove(key.ToLower());
}
public void RemoveAt(int index)
{
BaseRemoveAt(index);
}
public void Remove(string name)
{
BaseRemove(name);
}
public void Clear()
{
BaseClear();
// Add custom code here.
}
When trying to add using calling Add method -> Add(new TestElements() {Name = "check", ModelName ="checkname"}) -> this throws Configuration is readonly, looks BaseAdd is failing. Did I do something wrong?