user3688929
user3688929

Reputation: 23

Configuring a list in a .net configuration section

I'm having troubles writing a configuration section for my application. All I need is to config a list of pairs which I would translate to an object. I have seen implementations using ConfigurationElement and ConfigurationElementCollection classes, but it looks horrible, and I actually forced my code and configuration to fit this solution. I do NOT want to use element with key-value attributes becuase it's not what I need. I want my configuration section to look like this:

<MySection>
    <Option>
       <City>aaa</City>
       <Country>bbb</Country>
    </Option>
     <Option>
       <City>ccc</City>
       <Country>ddd</Country>
    </Option>
    <Option>
       <City>eee</City>
       <Country>fff</Country>
    </Option>
</MySection>

Another oossible section:

<MySection>
    <Option City="aaa" Country="bbb"/>
    <Option City="ccc" Country="ddd"/>
    <Option City="eee" Country="fff"/>
</MySection>

Is there any class that might help me parse this without forcing my code to do ugly stuff?

thank you

Upvotes: 1

Views: 188

Answers (1)

kloarubeek
kloarubeek

Reputation: 2844

You could go for 2 options:

  1. Create a custom configuration section at a similar question on How to add a xml in web.config? or have a loook at a basic example here: https://web.archive.org/web/20201202223151/http://www.4guysfromrolla.com/articles/020707-1.aspx

  2. If you can store it in a simple list, go for a comma separated string in your appSettings:

 <appSettings>
   <add key="countryName" value="CityA, CityC, CityD" />
   <add key="countryName2" value="CityB, CityE" />
 </appsettings>

And read it like this:

string[] citiesPerCountry = ConfigurationManager.AppSettings["countryName"].Split(',').Select(s => s.Trim()).ToArray();

Upvotes: 1

Related Questions