Reading keyvalue pairs into dictionary from app.config configSection

后端 未结 3 1407
北海茫月
北海茫月 2021-01-30 17:13

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

 

  

        
3条回答
  •  时光取名叫无心
    2021-01-30 17:20

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

    
      
        

    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 you can convert it like so:

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

提交回复
热议问题