简体   繁体   English

如何使用自定义配置节获取app.config值?

[英]How to get app.config value with using custom config sections…?

I want to get server address value, but I received a null reference exception in Alert method: 我想获取服务器地址值,但是在Alert方法中收到null reference exception

Values.Server.Key["CollectorServer"].Address -> null reference exception Values.Server.Key [“ CollectorServer”]。Address->空引用异常

My app.config looks like this: 我的app.config看起来像这样:

<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. 尝试此操作...如下配置您的应用程序。

<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 />");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM