user3165438
user3165438

Reputation: 2661

Dictionary equivalent to Config

I have a .config file which contains a couple of values.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="Element1" value="true"/>
    <add key="Element2" value="true"/>
    <add key="Element3" value="false"/>
  </appSettings>
</configuration>  

I would like to write them to a Dictionary structure. Is there a way to do so?

What if I have more than one config file - how can I manage the relevant ones?

Upvotes: 1

Views: 1030

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

You can use Linq to Xml

var settings = XDocument.Load(path_to_config)
                        .Root.Element("appSettings").Elements("add")
                        .ToDictionary(a => (string)a.Attribute("key"),
                                      a => (string)a.Attribute("value"));

But note, that <appSettings> element can also have <remove> and <clear> child elements. Which is not easy to treat. So, I'd go with usage of ConfigurationManager class which gives you dictionary-like access to app settings:

string element2 = ConfigurationManager.AppSettings["Element2"];

Or even

var settings = ConfigurationManager.AppSettings; // NameValueCollection
string element3 = settings["Element3"];

Upvotes: 2

Georgy Smirnov
Georgy Smirnov

Reputation: 391

I guess here's what you need:

ConfigurationManager.AppSettings.AllKeys.ToDictionary(k => k, k => ConfigurationManager.AppSettings[k]);

Upvotes: 2

Related Questions