Reading keyvalue pairs into dictionary from app.config configSection

痞子三分冷 提交于 2019-12-02 16:13:09
dkozl

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());

you'll need to add reference to System.Configuration assembly

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

<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 = section.Cast<DictionaryEntry>().ToDictionary(d => (string)d.Key, d => (string)d.Value);

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

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)
}

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!