我目前在我的应用程序中有一个 app.config 设置如下:
<?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<string, string>
中格式为 Dictionary<key, value>
.我已经使用 System.Configuration 尝试了几种不同的方法,但似乎都没有用,而且我无法找到我的确切问题的任何细节。有什么正确的方法可以做到这一点吗?
最佳答案
使用 ConfigurationManager
类,您可以从 app.config
文件中获取整个部分作为 Hashtable
,您可以将其转换为 Dictionary
如果你想:
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
程序集的引用
关于c# - 从 app.config 配置部分将键值对读入字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17663305/