Search code examples
c#.netconfigurationconfiguration-filesconfigurationmanager

Read part of appSettings from an external configuration file


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

Solution

  • 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>