[英]How to use ConfigurationManager.AppSettings with a custom section?
我需要从使用 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>
编辑:正如 CodeCaster 在他的回答中提到的, SingleTagSectionHandler
仅供内部使用。 我认为NameValueSectionHandler
是定义配置部分的首选方式。
此 API 支持 .NET Framework 基础结构,不应直接从您的代码中使用。
您可以将其作为HashTable
检索并使用Configuration.GetSection()
访问其条目:
Hashtable serverTag = (Hashtable)ConfigurationManager.GetSection("server");
string serverUrl = (string)serverTag["url"];
string peopleXMLPath = ConfigurationManager.AppSettings["server"];
从 app.config 文件的appSettings
部分获取值,但您将值存储在
<server url="http://example.com" />
将值放入appSettings
部分,如下所示,或者从其当前位置检索值。
您需要向配置的 appSettings 部分添加一个键值对。 如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="server" value="http://example.com" />
</appSettings>
</configuration>
您的阅读代码是正确的,但您可能应该检查是否为空。 如果代码无法读取配置值,则string
变量将为空。
您正在定义配置部分而不是AppSettings
中的值。 您可以简单地将您的设置添加到AppSettings
:
<appSettings>
... may be some settings here already
<add key="server" value="http://example.com" />
</appSettings>
自定义配置部分通常用于更复杂的配置(例如每个键多个值、非字符串值等。
如果要从应用设置中获取值,配置文件中的 appsetting 元素必须有一个键。
在配置部分下定义您的服务器值,如下所述:
<configuration>
<appSettings>
<add key="server" value="http://example.com" />
</appSettings>
...
...
...
</configuration>
现在执行以下代码行以获取服务器 url:
string peopleXMLPath = ConfigurationManager.AppSettings["server"].ToString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.