c# - 从外部配置文件中读取部分 appSettings

标签 c# .net configuration configuration-files configurationmanager

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

目前,我已经设置好了,但它似乎没有从 secrets.config 中读取,甚至没有告诉我读取失败。

在我的 app.config 中

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

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

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

在我的代码中

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

// secret turns out to be null

最佳答案

原来是我把外部文件的路径写错了

来自文档 on this page :

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

我将路径更改为以下路径:

<appSettings file = "..\..\secrets.config">
</appSettings>

关于c# - 从外部配置文件中读取部分 appSettings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33101748/

相关文章:

logging - 无法将 Serilog 配置转换为 appsettings.json

apache - 使用 FallbackResource 和大量虚拟主机配置的 HTTP 500

c# - 如何在 Visual Studio Code 中更新 C# 版本?

c# - 一种记录在 C# 中执行方法所花费时间的有效方法

c# - 有什么方法可以确定未知类型吗?

.net - 从 DispatcherObject 继承

c# - 组合依赖于其他可观察量的可观察量

c# - 如何判断当前应用是否为Medium Trust

.net - 在 Microsoft.Win32.OpenFileDialog 上调用 ShowDialog 时出现异常

debugging - 无法调试 pic32 微 Controller 或更新配置位