Custom configuration section in web.config or exe.config

 Let's build an example of custom configuration:

The final result should be like this:


<configSections>
    <section name="MySection"  type="Path.To.MyCustomSection, AssemblyName" />
</configSections>
<MySection>
    <rules default="supertest">
        <add title="test1" content="some test 1"/>
        <add title="test2" content="some test 2"/>
    </rules>
</MySection>

First we create the classes


public class MyCustomSection : ConfigurationSection
{
   [ConfigurationProperty("rules")]
   [ConfigurationCollection(typeof(RulesCollection), AddItemName = "add")]
   public RulesCollection Rules 
   { 
      get 
      { 
          return (RulesCollection)base["rules"]; 
      } 
   }
}

public class RulesCollection : ConfigurationElementCollection
{
   [ConfigurationProperty("default", IsRequired = true)]
   public string DefaultText {
      get { return (string)this["default"]; }
      set { this["default"] = value; }
   }

   protected override ConfigurationElement CreateNewElement()
   {
      return new CustomRuleElement ();
   }

   protected override object GetElementKey(ConfigurationElement element)
   {
      return ((CustomRuleElement )element).Type;
   }
}

public class CustomRuleElement : ConfigurationElement
{
   [ConfigurationProperty("title", IsRequired = true)]
   public string Title
   {
      get { return (string)this["title"]; }
      set { this["title"] = value; }
   }

   [ConfigurationProperty("text", IsRequired = true)]
   public string Text
   {
      get { return (string)this["text"]; }
      set { this["text"] = value; }
   }
}

And that is how we read the section content:


var customSection = ConfigurationManager.GetSection("MySection") as MyCustomSection;
Console.WriteLine(customSection.rules.OfType().FirstOrDefault()?.Text);

Post a Comment

Previous Post Next Post