Multiple AppSettings files, is it possible?

C#.NetConfigurationAppsettings

C# Problem Overview


I want to create 3 AppSettings config files:

  • Database.config
  • Messages.config
  • Global.config

And after add in my App.config:

<appSettings file="Database.config" />
<appSettings file="Messages.config" />
<appSettings file="Global.config" />

But when I try to access a key that there is in one of three files with the ConfigurationManager, I got the following error:

>Configuration system failed to initialize. Sections must only appear once per config file.

I cannot have more than one AppSettings config file?

C# Solutions


Solution 1 - C#

You can't have more than one appsettings because that's the name of a section. You can add a new section though that uses the same kind of section definition as appsettings. E.g.,

<configuration>
    <configSections>
        <section name="DatabaseConfig" type="System.Configuration.NameValueFileSectionHandler, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
    </configSections>
    ....
    <DatabaseConfig>
       <add key="Whatever" value="stuff"/>
    </DatabaseConfig>
</configuration>

Solution 2 - C#

Code for separate file:

Web.config:

<configSections>
    <section name="DatabaseConfig" type="System.Configuration.NameValueFileSectionHandler, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    <section name="MessageConfig" type="System.Configuration.NameValueFileSectionHandler, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    <section name="GlobalConfig" type="System.Configuration.NameValueFileSectionHandler, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>

<DatabaseConfig configSource="database.config">
</DatabaseConfig>

<MessageConfig configSource="message.config">
</MessageConfig>

<GlobalConfig configSource="global.config">
</GlobalConfig>

database.config:

<DatabaseConfig>
  <add key="Name" value="ServerName" />
</DatabaseConfig>

etc...

Can be accessed via code like this:

var databaseConfiguration = (NameValueCollection)ConfigurationManager.GetSection("DatabaseConfig");
string name = databaseConfiguration["Name"];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVinicius OttoniView Question on Stackoverflow
Solution 1 - C#aquinasView Answer on Stackoverflow
Solution 2 - C#OgglasView Answer on Stackoverflow