我需要从使用App.config文件获得“
http://example.com”.
但目前我正在使用:
string peopleXMLPath = ConfigurationManager.AppSettings["server"];
我无法获得价值.
你能指出我做错了什么吗?
<?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>
解决方法
我认为您需要获取配置部分,并访问:
var section = ConfigurationManager.GetSection("server") as NameValueCollection; var value = section["url"];
您还需要更新配置文件:
<?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>
编辑:As CodeCaster mentioned in his answer,SingleTagSectionHandler仅供内部使用.我认为NameValueSectionHandler是定义配置节的首选方式.