如何使用ConfigurationManager.AppSettings与自定义栏目? [英] How to use ConfigurationManager.AppSettings with a custom section?
本文介绍了如何使用ConfigurationManager.AppSettings与自定义栏目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用App.config文件获得 http://example.com 。
但目前我使用的:
字符串peopleXMLPath = ConfigurationManager.AppSettings [服务器];
我不能得到的值。
你能指出我在做什么错了?
< XML版本=1.0编码=UTF-8&GT?;
<结构>
< configSections>
<节名称=设备TYPE =System.Configuration.SingleTagSectionHandler/>
<节名称=服务器类型=System.Configuration.SingleTagSectionHandler/>
< / configSections>
<设备ID =1说明=PETRAS房位置=商场=/>
<服务器URL =http://example.com/>
< /结构>
解决方案
我想你需要获得配置节,并访问:
VAR部分= ConfigurationManager.GetSection(服务器)作为NameValueCollection中;
VAR值=节[网址];
你还需要更新你的配置文件:
< XML版本=1.0编码=UTF-8&GT?;
<结构>
< configSections>
<节名称=设备TYPE =System.Configuration.NameValueSectionHandler/>
<节名称=服务器类型=System.Configuration.NameValueSectionHandler/>
< / configSections>
<装置>
<添加键=ID值=1/>
<添加键=说明值=PETRAS室/>
<添加键=位置值=/>
<添加键=商城值=/>
< /装置>
<服务器>
<添加键=URL值=http://example.com/>
< /服务器>
< /结构>
编辑:正如他的回答提到的codeCaster, SingleTagSectionHandler
仅供内部使用。我觉得 NameValueSectionHandler
是preferred的方式来定义的配置部分。
I need to get "http://example.com" from using App.config file.
But at the moment I am using:
string peopleXMLPath = ConfigurationManager.AppSettings["server"];
I cannot get the value.
Could you point out what I am doing wrong?
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<configSections>
<section name="device" type="System.Configuration.SingleTagSectionHandler" />
<section name="server" type="System.Configuration.SingleTagSectionHandler" />
</configSections>
<device id="1" description="petras room" location="" mall="" />
<server url="http://example.com" />
</configuration>
解决方案
I think you need to get the config section, and access that:
var section = ConfigurationManager.GetSection("server") as NameValueCollection;
var value = section["url"];
And you also need to update your config file:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<configSections>
<section name="device" type="System.Configuration.NameValueSectionHandler" />
<section name="server" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<device>
<add key="id" value="1" />
<add key="description" value="petras room" />
<add key="location" value="" />
<add key="mall" value="" />
</device>
<server>
<add key="url" value="http://example.com" />
</server>
</configuration>
Edit: As CodeCaster mentioned in his answer, SingleTagSectionHandler
is for internal use only. I think NameValueSectionHandler
is the preferred way to define config sections.
这篇关于如何使用ConfigurationManager.AppSettings与自定义栏目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文