Howiecamp
Howiecamp

Reputation: 3111

How can I implement per-project appSettings and global appSettings across multiple Visual Studio projects?

I've got multiple projects in a Visual Studio solution and I've got some settings which are project-specific and others which are global. Configuration file wise I want to accomplish the following:

My plan was to use the ability of the file attribute in <appSettings file="..."> to merge in the per-project and global settings as follows:

WebProject1's web.config:

  <appSettings file="WebProject1.config">
    <add key="WebProject1Setting1" value="WebProject 1 Setting 1" />
  </appSettings>

WebProject1.config:

  <appSettings file="Global.config">
    <add key="WebProject1Secret1" value="WebProject 1 Secret 1" />
  </appSettings>

Global.config:

  <appSettings>
    <add key="GlobalSetting1" value="Global setting 1" />
  </appSettings>

Apparently however only the top level web.config can include another config file, as I get the following error on build:

Unrecognized attribute 'file'. Note that attribute names are case-sensitive.

Source Error:

Error

My objective here was to define the settings that are common to all projects in Global.config and then define project-specific settings in the top level web.config files as well as in the included config files like WebProject1.config.

Any suggestions?

Upvotes: 2

Views: 1038

Answers (1)

Hem Acharya
Hem Acharya

Reputation: 258

You cannot nest the inclusion of config files. ie. a web/app.config appsetting including another setting file which in turn including yet another setting file and so on. The file attribute on appsetting only works on main web/app.config file.

To achieve what you want you can use a separate section in web.config file of each project for secret settings.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

<configSections>
<section name="SecretSettings" 
type="System.Configuration.NameValueFileSectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"></section>
</configSections>

<SecretSettings configSource="secretsettings.config"></SecretSettings>

<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<appSettings>
</appSettings>

</configuration>

Now access your settings from program like

var secretSettings =(NameValueCollection)ConfigurationManager.GetSection("SecretSettings");

Make sure the file secretsettings.config is set to copy always to output folder in its properties.

Upvotes: 4

Related Questions