redcalx
redcalx

Reputation: 8637

What is the most convenient way of handling nested config data in .Net?

I often store application config data in an app.config file in the following format:

<configuration>
    <appSettings>
        <add key="foo" value="foo value"/>
        <add key="bar" value="bar value"/>
     </appSettings>
</configuration>

This can then be easily accessed at runtime with:

string fooValue = ConfigurationManager.AppSettings["foo"];

However this approach does not seem to allow for handling nested/hierarchichal data or multiple items with the same key, e.g. I want to be able to list a number of config items that specify namespace prefix/uri pairs.

I'm findign the documentation is somewhat confusing so was wondering what the consensus was on the easiest/quickest and most convenient way of dealing with nested application config data. This is a simple per application/installation configuration - not per user.

Upvotes: 1

Views: 1333

Answers (3)

user1921
user1921

Reputation:

For web apps in the past I've used a key in the machine.config to identify the environment (i.e. QA, UAT, Prod, etc.) and then in the web.config used keys like this:

machine.config

        <add key="server_environment" value="qa"/>

web.config

<configuration>
    <appSettings>
        <add key="qa_foo" value="foo value"/>
        <add key="uat_foo" value="foo value"/>
        <add key="prod_foo" value="foo value"/>
     </appSettings>
</configuration>

I get the server_environment value and pair it with the key I'm looking for - changing the environment is as simple as changing the value in the machine.config. As has been mentioned already, section groups are something you'll probably want to investigate as well.

Upvotes: 0

JonoW
JonoW

Reputation: 14229

Look into section groups: http://www.codeproject.com/KB/aspnet/Managing_Webconfig.aspx

Lets you write custom XML fragments in web.config that your custom handler can parse. That allows you to set up more complex configuration options.

Upvotes: 2

azheglov
azheglov

Reputation: 5523

I'd recommend defining your own XML schema for such hierarchical settings and serializing it to / deserializing from a configuration file on the disk (separate from app.config/web.config)

Upvotes: 2

Related Questions