微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如何将ConfigurationManager.AppSettings与自定义部分一起使用?

我需要从使用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是定义配置节的首选方式.

原文地址:https://www.jb51.cc/csharp/92248.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐