从外部配置文件中读取appSettings的一部分

Wat*_* v2 7 .net c# configuration configurationmanager configuration-files

我想appSettings从一个名为的外部配置文件中读取我的控制台应用程序的一部分secrets.config,而其余​​的我希望从中读取app.config.

目前,我有这个设置,但它似乎没有读取secrets.config,它甚至没有告诉我有关读取失败.

在我的app.config中

<appSettings file = "secrets.config">
  <add key = "Foo" value = "Bar" />
</appSettings>
Run Code Online (Sandbox Code Playgroud)

在secrets.config中,它与app.config位于同一文件夹中

<appSettings>
  <add key = "Secret" value = "Tiger" />
</appSettings>
Run Code Online (Sandbox Code Playgroud)

在我的代码中

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

// secret turns out to be null
Run Code Online (Sandbox Code Playgroud)

Wat*_* v2 6

原来,我将外部文件的路径写为错误的路径。

从此页面上的文档中:

指定的路径是相对于主配置文件的。对于Windows Forms应用程序,这将是二进制文件夹(例如/ bin / debug),而不是应用程序配置文件的位置。对于Web Forms应用程序,该路径是相对于应用程序根目录的,该目录是web.config文件所在的位置。

在工作时,我将路径更改为以下内容:

<appSettings file = "..\..\secrets.config">
</appSettings>
Run Code Online (Sandbox Code Playgroud)