关于c#:如何使用自定义配置部分获取app.config值…?

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

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

0

我的app.config如下:

1
2
3
4
5
6
7
<configSections>
  <section requirePermission="false"  name="serverlist" type="SampleConsole.CustomAppTest, SampleConsole"></section>
</configSections>

<serverlist>
  </add>
</serverlist>

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<serverfulllist>
    <serverlist>
     
    </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 />");
    }
}