C# 将键值对从 app.config configSection 读入字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17663305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:08:11  来源:igfitidea点击:

Reading keyvalue pairs into dictionary from app.config configSection

c#wpfxmldictionaryapp-config

提问by DanteTheEgregore

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

我目前在我的应用程序中有一个 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>

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?

我目前的目标是 foreach 或简单地将 MajorCommands 中的所有值读取Dictionary<string, string>Dictionary<key, value>. 我使用 System.Configuration 尝试了几种不同的方法,但似乎都没有工作,而且我无法找到任何关于我的确切问题的详细信息。有没有合适的方法来做到这一点?

采纳答案by dkozl

using ConfigurationManagerclass you can get whole section from app.configfile as Hashtablewhich you can convert to Dictionaryif you want to:

使用ConfigurationManagerclass 您可以从app.config文件中获取整个部分HashtableDictionary如果您愿意,可以将其转换为:

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

you'll need to add reference to System.Configurationassembly

您需要添加对System.Configuration程序集的 引用

回答by sora0419

I would probably treat the config file as an xml file.

我可能会将配置文件视为 xml 文件。

Dictionary<string, string> myDictionary = new Dictionary<string, string>();
XmlDocument document = new XmlDocument();
document.Load("app.config");
XmlNodeList majorCommands = document.SelectNodes("/configuration/DeviceSettings/MajorCommands/add");

foreach (XmlNode node in majorCommands)
{
    myDictionary.Add(node.Attributes["key"].Value, node.Attributes["value"].Value)
}

If document.Load doen't work, try converting your config file to xml file.

如果 document.Load 不起作用,请尝试将您的配置文件转换为 xml 文件。

回答by Shaun McCarthy

You are almost there - you just have nested your MajorCommands a level too deep. Just change it to this:

你就快到了——你只是把你的 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>

And then the following will work for you:

然后以下内容对您有用:

var section = (Hashtable)ConfigurationManager.GetSection("MajorCommands");
Console.WriteLine(section["Reset"]);

Note that this is a Hashtable (not type safe) as opposed to a Dictionary. If you want it to be Dictionary<string,string>you can convert it like so:

请注意,这是一个哈希表(不是类型安全的)而不是字典。如果你想要它,Dictionary<string,string>你可以像这样转换它:

Dictionary<string,string> dictionary = section.Cast<DictionaryEntry>().ToDictionary(d => (string)d.Key, d => (string)d.Value);