从 app.config configSection 将键值对读入字典 [英] Reading keyvalue pairs into dictionary from 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 中的所有值读取到 Dictionary
格式为 Dictionary
.我使用 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
如果需要,您可以将其转换为 Dictionary
:
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
程序集的引用
you'll need to add reference to System.Configuration
assembly
这篇关于从 app.config configSection 将键值对读入字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!