【问题标题】:How to get app.config value with using custom config sections...?如何使用自定义配置部分获取 app.config 值...?
【发布时间】:2016-05-02 16:58:39
【问题描述】:

我想获取服务器地址值,但我在 Alert 方法中收到了null reference exception

Values.Server.Key["CollectorServer"].Address -> 空引用 异常

我的 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>

我的自定义配置部分如下所示:

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; }
    }
}}

【问题讨论】:

  • 看看this thread,或许对你有帮助
  • 如果您所做的只是添加键/值设置类型,那么只需使用 appsettings 配置部分

标签: c# nullreferenceexception configsection


【解决方案1】:

试试这个... 使您的应用配置如下。

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

【讨论】:

  • if (address != null) { foreach (string key in address.AllKeys) { Response.Write(key + ": " + address[key] + "
    "); } } else { console.write("没有对象...");
猜你喜欢
  • 2011-10-02
  • 2015-07-05
  • 2011-05-25
  • 2011-11-21
  • 2012-10-04
  • 2012-01-28
  • 2011-12-10
  • 1970-01-01
  • 2010-10-20
相关资源
最近更新 更多