读键值对到字典从app.config中configSection [英] Reading keyvalue pairs into dictionary from app.config configSection

查看:990
本文介绍了读键值对到字典从app.config中configSection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在我的一个应用程序中设置像这样一个app.config:

I currently have an app.config in an application of mine set up like so:

 <?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="DeviceSettings">
      <section name="MajorCommands" type="System.Configuration.DictionarySectionHandler"/>
    </sectionGroup>
  </configSections>
  <appSettings>
    <add key="ComPort" value="com3"/>
    <add key="Baud" value="9600"/>
    <add key="Parity" value="None"/>
    <add key="DataBits" value="8"/>
    <add key="StopBits" value="1"/>
    <add key="Ping" value="*IDN?"/>
    <add key="FailOut" value="1"/>
  </appSettings>
  <DeviceSettings>
    <MajorCommands>
      <add key="Standby" value="STBY"/>
      <add key="Operate" value="OPER"/>
      <add key="Remote" value="REMOTE"/>
      <add key="Local" value="LOCAL"/>
      <add key="Reset" value="*RST" />
    </MajorCommands>
  </DeviceSettings>
</configuration>



我现在的目标是的foreach或只是读取MajorCommands所有值成字典<字符串,字符串> 格式为词典<关键字,值> 。我试着用System.Configuration几种不同的方法,但似乎没有任何工作,我一直无法找出有什么细节我确切的问题。是否有这样做的正确方法?

My current objective is to foreach or simply read all values from MajorCommands into a Dictionary<string, string> formatted as Dictionary<key, value>. I've tried several different approaches using System.Configuration but none seem to work and I haven't been able to find any details out there for my exact question. Is there any proper way to do this?

推荐答案

使用 ConfigurationManager中类你可以从的app.config 文件全断面为的Hashtable ,你可以转换为词典如果你想:

using ConfigurationManager class you can get whole section from app.config file as Hashtable which you can convert to Dictionary if you want to:

var section = (ConfigurationManager.GetSection("DeviceSettings/MajorCommands") as System.Collections.Hashtable)
                 .Cast<System.Collections.DictionaryEntry>()
                 .ToDictionary(n=>n.Key.ToString(), n=>n.Value.ToString());

您需要添加引用 System.Configuration 组装

这篇关于读键值对到字典从app.config中configSection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆