【问题标题】:How to read app.config from another assembly?如何从另一个程序集中读取 app.config?
【发布时间】:2011-06-20 20:03:51
【问题描述】:

我有两个项目:

  • 控制台项目 (Test.exe)
  • 类库项目 (Test.Data.dll)

我的类库项目包含一个app.config 文件。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="TestEntities" connectionString="metadata=res://*/DBNews.csdl|res://*/DBNews.ssdl|res://*/DBNews.msl;provider=System.Data.SqlClient;provider connection string=&quot;{0}&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>

我想从控制台项目访问类库中的设置,所以我尝试了:

var config = ConfigurationManager.OpenExeConfiguration("Test.Data.dll");
config.ConnectionStrings.ConnectionStrings[0].Name; // LocalSqlServer
// seems to be the wrong assembly.

还有:

var config = ConfigurationManager.OpenExeConfiguration("Test.Data.dll.config");
// invalid exePath

如何访问 DLL 的 app.config

【问题讨论】:

标签: c# app-config


【解决方案1】:

DLL 在运行时没有自己的 app.config。 app.config 仅适用于实体框架设计器。

在执行期间,DLL 将尝试从应用程序的 app.config 文件中读取值。对于实体框架连接,这意味着您必须将连接信息复制到应用程序的 app.config 中。

【讨论】:

    【解决方案2】:

    .NET 最多只能为一个正在执行的程序集加载一个 App.config 文件。如果您的附属程序集有 App.config 文件,它们将不会被执行程序集解析。

    为了从附属程序集的 App.config 中获取设置,您必须将这些设置移动(复制)到正在执行的程序集的 App.config 中。

    【讨论】:

      【解决方案3】:

      我是这样解决的。假设您的程序集及其 .config 文件中的连接字符串是您项目中的一个引用,因此与正在执行的程序集一起存在。

      String AssemblyName = "MyAssemblyWithConfig.dll";
      String appConfigPath = new FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\" + AssemblyName + ".config";
      System.AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", appConfigPath);
      string connectionString = ConfigurationManager.ConnectionStrings["TestEntities"].ConnectionString;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-11
        • 2013-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-21
        • 2012-07-16
        • 2012-07-30
        相关资源
        最近更新 更多