Home > ASP.NET, C# > Custom configuration section in app.config e web.config

Custom configuration section in app.config e web.config

Qualche giorno fa mi sono dilettato nella creazione si una custom section in un file di configurazione. Dopo un pò di ricerche ho scritto quanto segue. Ogni suggerimento è graditissimo…

using System;
using System.Collections.Generic;
using System.Configuration;

namespace Naked
{
    public sealed class NakedConfigSection : ConfigurationSection
    {
        [ConfigurationProperty( "Config" )]
        public NakedElementCollection NakedItems
        {
            get { return ((NakedElementCollection)(base["Config"])); }
        }
    } public class NakedElement : ConfigurationElement
    {
        [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; }
        }
    }

    [ConfigurationCollection(typeof(NakedElement))]
    public class NakedElementCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new NakedElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((NakedElement)(element)).Key;
        }

        public NakedElement this[int idx]
        {
            get
            {
                return (NakedElement)BaseGet(idx);
            }
        }
    }

}

nel file di config settiamo quanto segue:

<configSections>
  <section name=”NakedConfigutation” type=”Naked.NakedConfigSection, Naked”/>
</configSections>

<NakedConfigutation>
  <Config>
    <add key=”1″ value=”100″/>
    <add key=”2″ value=”200″/>
    <add key=”3″ value=”300″/>
    <add key=”4″ value=”400″/>
  </Config>
</NakedConfigutation>

così richiamiamo i nuovi parametri:

Naked.NakedConfigSection section = (Naked.NakedConfigSection)ConfigurationManager.GetSection(“NakedConfigutation”);
string test = section.NakedItems["1"];

Categorie:ASP.NET, C# Tag: , ,