nul..." /> nul..." /> nul..."/>

How to get app.config value with using custom config sections...?

757 views Asked by At

I want to get server address value, but I received a null reference exception in Alert method:

Values.Server.Key["CollectorServer"].Address -> null reference exception

My app.config looks like this:

<configSections>
  <section requirePermission="false"  name="serverlist" type="SampleConsole.CustomAppTest, SampleConsole"></section>
</configSections>

<serverlist>
  <add name="CollectorServer" address="127.0.0.1"></add>
</serverlist>

My custom config section looks like this:

namespace SampleConsole
{
public class CustomAppTest
{
    public void Alert()
    {

        Console.WriteLine(Values.Server.Key["CollectorServer"].Address);
    }
}


public class Values
{

    public static ServerValues Server = ConfigurationManager.GetSection("serverlist") as ServerValues;

}


public class ServerValues : ConfigurationSection
{

    [ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
    public ServerCollection Key
    {
        get { return (ServerCollection)this[""]; }
        set { this[""] = value; }
    }
}


public class ServerCollection : ConfigurationElementCollection
{

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


    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((ServerElement)element).Name;
    }


    public new ServerElement this[string elementName]
    {
        get
        {
            return this.OfType<ServerElement>().FirstOrDefault(item => item.Name == elementName);
        }
    }
}

public class ServerElement : ConfigurationElement
{

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


    [ConfigurationProperty("address", IsRequired = true)]
    public string Address
    {
        get { return (string)base["address"]; }
        set { base["address"] = value; }
    }
}}
1

There are 1 answers

1
Furquan Khan On

Try this... Make your app config as below.

<serverfulllist>
    <serverlist>
      <add name="CollectorServer" value="127.0.0.1"/>
    </serverlist>
</serverfulllist>
NameValueCollection address =  
ConfigurationManager.GetSection("serverfulllist/serverlist")
as System.Collections.Specialized.NameValueCollection;

if (address != null)
{
    foreach (string key in address.AllKeys)
    {
       Response.Write(key + ": " + address[key] + "<br />");
    }
}