10

I'd like to read a part of the appSettings of my console application from an external configuration file named, say, secrets.config, while the rest of it I would like to read from the app.config.

Presently, I have this set up but it seems like it isn't reading from secrets.config and it isn't even telling me about the read failure.

In my app.config

<appSettings file = "secrets.config">
  <add key = "Foo" value = "Bar" />
</appSettings>

In secrets.config, which is in the same folder as app.config

<appSettings>
  <add key = "Secret" value = "Tiger" />
</appSettings>

In my code

var secret = ConfigurationManager.AppSettings["Secret"];

// secret turns out to be null
Water Cooler v2
  • 32,724
  • 54
  • 166
  • 336
  • Possible duplicate of [ConfigurationManager.AppSettings use another config file](http://stackoverflow.com/questions/16425407/configurationmanager-appsettings-use-another-config-file) – James Thorpe Oct 13 '15 at 11:44
  • 1
    Hmm sorry, just realised you're already taking one of the approaches detailed in an answer on that Q. – James Thorpe Oct 13 '15 at 11:45

1 Answers1

7

It turns out that I was writing the path of the external file as the wrong path.

From the documentation on this page:

The path specified is relative to the main configuration file. For a Windows Forms application, this would be the binary folder (such as /bin/debug), not the location of the application configuration file. For Web Forms applications, the path is relative to the application root, where the web.config file is located.

I changed the path to the following at it worked:

<appSettings file = "..\..\secrets.config">
</appSettings>
Water Cooler v2
  • 32,724
  • 54
  • 166
  • 336
  • 1
    Same thing worked for me. If the app.SECRETS.config is adjacent to app.config. i.e. `` – Tim Reilly Jun 22 '17 at 20:08
  • A little late to the party, but you could've make it work without changing the path by instructing Visual Studio to copy the file to the output folder on build. This is done by right clicking the file in the Solution Explorer > Properties, then Copy to Output Directory = Copy if newer or Copy Always. – Ronald Rey Jul 28 '17 at 18:55