Search code examples
c#asp.netweb-configcustom-configuration

Is there any way to access the value of custom config section using the key as in AppSettings?


I have a customized config section in my web.config like this:

     <configSection>
            <section name="CustomConfig" type="ConfigSectionRoot" allowLocation="true" allowDefinition="Everywhere"/>
        </configSection>


    <CustomConfig>
    <ConfigRoot>
        <add key="DataBase" value="CouchDB"/>
        <add key="FrontEnd" value="Asp.Net"/>
        <add key="AppName" value="Virtual WorkPlace"/>
      </ConfigRoot>
    </CustomConfig>

<AppSettings>
<add key="DataBase" value="CouchDB"/>
</AppSettings>

My ConfigSectionRoot.cs is like this:

public class ConfigSectionRoot:ConfigurationSection
    {

        [ConfigurationProperty("key", DefaultValue = "", IsKey = true, IsRequired = true)]
        public string Key
        {
            get
            {
                return ((string)(base["key"]));
            }
            set
            {
                base["key"] = value;
            }
        }

        [ConfigurationProperty("value", DefaultValue = "", IsKey = false, IsRequired = false)]
        public string Value
        {
            get
            {
                return ((string)(base["value"]));
            }
            set
            {
                base["value"] = value;
            }
        }
    }

If i use AppSettings Instead of Custom Config I could access it like:

string results= ConfigurationManager.AppSettings["Database"];
// results wil contain "CouchDB"

Is there any way to achieve the same thing in Customized Config section ??? Pls help me out


Solution

  • NameValueSectionHandler

    If your configuration doesn't need to be more than a key-value store, I'd go for a NameValueSectionHandler.

    <section name="customConfig" type="System.Configuration.NameValueSectionHandler"/>
    <!-- ... -->
    <customConfig>
      <add key="DataBase" value="CouchDB" />
      <add key="FrontEnd" value="Asp.Net" />
      <add key="AppName" value="Virtual WorkPlace" />
    </customConfig>
    

    You can then read it out, just like the appSettings:

    var customConfig = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationManager.GetSection("customConfig");//i have changed like this and it worked fine
    var database = customConfig["DataBase"];
    

    SingleTagSectionHandler

    You could also achieve the same with a SingleTagSection:

    <section name="customConfig" type="System.Configuration.SingleTagSectionHandler"/>
    <!-- ... -->
    <customConfig database="CouchDB" frontEnd="Asp.Net" appName="Virtual Workplace" />
    

    And then query it with:

    var customConfig = (System.Collections.Hashtable) System.Configuration.ConfigurationManager.GetConfig("customConfig");
    var database = customConfig["database"];