【问题标题】:application not reading from user.config应用程序未从 user.config 读取
【发布时间】:2026-01-29 07:15:01
【问题描述】:

我有包含 asp.net 和控制台应用程序项目的 Visual Studio 解决方案。在控制台应用程序中,我有 app.config 我这样声明它应该从 user.config 读取

  <appSettings  file="user.config">

  </appSettings>

这是我的 user.config

<appSettings>

  <add key="MyKey" value="Test" />

</appSettings>

然后在我的代码中我尝试获取类似

 string myKey = ConfigurationManager.AppSettings["MyKey"];

但它给了我null。这里有什么问题以及如何解决?

更新 1 我已将 app.config 和 user.config 的 Copy to Output 目录设置为 Copy Always

【问题讨论】:

  • 您确定 user.config 存在于应用程序目录中吗?你每次都把它复制到输出目录吗?为什么不尝试指定该文件的绝对路径。
  • 您是否在 appconfig 中有一个 部分并进行了 System.Configuration 参考?
  • @Bebolicious offcourse 我在 app.config 中有配置部分。我只是没有包含在 SO
  • @James 你不能责怪他们问什么时候它不包含在问题中。
  • @Amy 没有怪罪。我只是告诉我没有包含在 SO

标签: c# console-application


【解决方案1】:

user.config 必须与app.config 存在于同一目录中;如果在运行时找不到该文件,它将使用来自app.config 的值(不存在),所以你得到null。确保 user.config 配置为在构建时复制到输出目录,并且构建操作设置为“无”。

构建项目后,config 文件是否都存在于输出目录中?

【讨论】:

  • user.config 和 app.config 都在同一级别
  • @James 他们都是在构建时“复制到输出文件夹”吗?
  • @Amy 是的,我将复制到输出目录设置为始终复制
  • @James 请将该信息添加到您的问题中,这样人们就不需要通过 cmets 来寻找您问题的完整图片。
  • 我不知道发生了什么,但看起来它现在正在工作:)
最近更新 更多