Reading keyvalue pairs into dictionary from app.config configSection

63,781

Solution 1

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

Solution 2

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);
Share:
63,781

Related videos on Youtube

DanteTheEgregore
Author by

DanteTheEgregore

Other Links Stack Exchange is now openly publishing the DMCA Notices they receive on Chilling Effects. We Hate Fun W3Fools - A W3Schools Intervention XKCD

Updated on July 09, 2022

Comments

  • DanteTheEgregore
    DanteTheEgregore almost 2 years

    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>
    

    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?

    • MattDavey
      MattDavey over 8 years
      For future generations coming across this question as I did - when running under mono the section type must be System.Configuration.DictionarySectionHandler, System - the System part is crucial.
  • DanteTheEgregore
    DanteTheEgregore almost 11 years
    The .ToDictionary(n=>n.Key, n=>n.Value); needs to be .ToDictionary(n=>n.Key.ToString(), n=>n.Value.ToString());. Other than that the answer works perfectly with little added code. Thank you!
  • Shaun McCarthy
    Shaun McCarthy almost 11 years
    see @dkozl's answer as to how to do this without removing the nesting (with the path "DeviceSettings/MajorCommands")
  • arviman
    arviman over 7 years
    Doesn't work for me in 4.5.2. The object is a NameValueCollection, not a HashTable.
  • Oğuzhan Kahyaoğlu
    Oğuzhan Kahyaoğlu almost 7 years
    yeah, i was searching for this for years. I used to develop configsections via ConfigSectionDesigner, but this rocks.. btw, i searched similar base types about handling config values via MSDN, there is only one useful thing: msdn.microsoft.com/en-us/library/…
  • Nick
    Nick almost 7 years
    Works fine in 4.5 and 4.6. Make sure your configSections entry in your app/web.config is DictionarySectionHandler and not NameValueSectionHandler. The latter will give you a ReadOnlyNameValueCollection instead of a Hashtable.
  • justdan23
    justdan23 over 4 years
    The problem with this approach is the sections may be encrypted. The ConfigurationManager class knows how to decrypt and read them when on the same server they were encrypted on, so you definitely want to use the ConfigurationManager class here.
  • JacobIRR
    JacobIRR over 4 years
    This works for me in a webconfig file, but not in an app.config for unit testing. When I try to run unit tests with this kind of dictionary structure in the app config, the tests don't run. They run when I remove it...
  • Admin
    Admin over 4 years
    Change type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" and it will work in the app.Config.
  • Rajesh Mishra
    Rajesh Mishra about 4 years
    Although, there are few typo but this was the simplest approach that worked for me since I didnt have to write those custom classes like other approaches were telling. I needed to read more than 1 config files and a custom section inside them. This is the only things that helped. Thanks.