App.config 带 dll returns 空

App.config with dll returns null

我有一个从另一个应用程序调用的 dll。我需要将 dll 设置存储在单独的 xml 文件中。所以我创建了 App.config 文件。它看起来像:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="myKey" value="1"/>
  </appSettings>
</configuration>

然后我尝试使用 thic 代码从配置中获取值:

var val=System.Configuration.ConfigurationSettings.AppSettings["myKey"];

但它始终 return 为空。 AppSettings 的键数也为零,因此其中没有键。

这是怎么回事? 如何将我的设置存储在单独的文件中?

确保您问题中提到的配置在调用应用程序的配置文件中,而不是在 DLL 的 App.config 中。

如果我没记错的话,你正在寻找 ConfigurationManager.OpenMappedExeConfiguration Method (ExeConfigurationFileMap, ConfigurationUserLevel)

您需要将该程序集配置文件作为另一个 Configuration 对象打开,一旦您获得它,您就可以访问那些 AppSettings.