加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:15:06 所属栏目:百科 来源:网络整理
导读:我需要从使用App.config文件获得“ http://example.com”. 但目前我正在使用: string peopleXMLPath = ConfigurationManager.AppSettings["server"]; 我无法获得价值. 你能指出我做错了什么吗? ?xml version="1.0" encoding="UTF-8"?configuration configS
我需要从使用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是定义配置节的首选方式.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读