我目前在我的应用程序中有一个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>
我目前的目标是预先或简单地将MajorCommands中的所有值读取为格式为Dictionary<string, string>
的{{1}}。我已经尝试了几种使用System.Configuration的不同方法,但似乎没有工作,我无法找到任何细节,我的确切问题。有没有正确的方法来做到这一点?
答案 0 :(得分:48)
使用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
程序集
答案 1 :(得分:39)
你几乎就在那里 - 你刚刚将你的MajorCommands嵌套得太深了。只需将其更改为:
<configuration>
<configSections>
<section
name="MajorCommands"
type="System.Configuration.DictionarySectionHandler" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<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>
</configuration>
然后以下内容适合您:
var section = (Hashtable)ConfigurationManager.GetSection("MajorCommands");
Console.WriteLine(section["Reset"]);
请注意,这是一个Hashtable(不是类型安全的)而不是Dictionary。如果您希望它为Dictionary<string,string>
,您可以将其转换为:
Dictionary<string,string> dictionary = section.Cast<DictionaryEntry>().ToDictionary(d => (string)d.Key, d => (string)d.Value);
答案 2 :(得分:-1)
我可能会将配置文件视为xml文件。
Dictionary<string, string> myDictionary = new Dictionary<string, string>();
XmlDocument document = new XmlDocument();
document.Load("app.config");
XmlNodeList mejorCommands = doc.SelectNodes("/configuration/DeviceSettings/MajorCommands/add");
foreach (XmlNode node in majorCommands)
{
myDictionary.Add(node.Attributes["key"].Value, node.Attributes["value"].Value)
}
如果document.Load不起作用,请尝试将配置文件转换为xml文件。