如何从另一个程序集中读取app.config?

Bru*_*oLM 15 c# app-config

我有两个项目:

  • 控制台项目(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>
Run Code Online (Sandbox Code Playgroud)

从Console项目我想从类库中访问设置,所以我尝试过:

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

和:

var config = ConfigurationManager.OpenExeConfiguration("Test.Data.dll.config");
// invalid exePath
Run Code Online (Sandbox Code Playgroud)

我该如何访问DLL app.config

Jus*_*ner 11

DLL在运行时没有自己的app.config.app.config仅适用于Entity Framework设计器.

在执行期间,DLL将尝试从Application的app.config文件中读取值.对于Entity Framework连接,这意味着您必须将连接信息复制到Application的app.config中.


Nat*_*lor 6

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

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