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; }
}
}}
Try this... Make your app config as below.