【问题标题】:Read part of appSettings from an external configuration file从外部配置文件中读取 appSettings 的一部分
【发布时间】:2016-01-11 03:35:23
【问题描述】:

我想从名为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

【问题讨论】:

标签: c# .net configuration configuration-files configurationmanager


【解决方案1】:

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

来自文档on this page

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

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

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

【讨论】:

  • 同样的事情对我有用。如果 app.SECRETS.config 与 app.config 相邻。即&lt;appSettings file="..\..\App.SECRETS.config"&gt;
  • 聚会有点晚了,但是您可以通过指示 Visual Studio 将文件复制到构建时的输出文件夹来使其工作而无需更改路径。这是通过右键单击解决方案资源管理器 > 属性中的文件,然后复制到输出目录 = 如果较新则复制或始终复制。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-30
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 2020-11-18
  • 1970-01-01
相关资源
最近更新 更多