如何从另一个程序集读取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="{0}"" 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
?
I have two projects:
- Console project (Test.exe)
- Class Library project (Test.Data.dll)
My Class Library project contains an app.config
file.
<?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="{0}"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
From the Console project I want to access the settings from the Class Library, so I've tried:
var config = ConfigurationManager.OpenExeConfiguration("Test.Data.dll");
config.ConnectionStrings.ConnectionStrings[0].Name; // LocalSqlServer
// seems to be the wrong assembly.
And:
var config = ConfigurationManager.OpenExeConfiguration("Test.Data.dll.config");
// invalid exePath
How can I access the DLL's app.config
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
该 DLL 在运行时没有自己的 app.config。 app.config 仅适用于实体框架设计器。
在执行期间,DLL 将尝试从应用程序的 app.config 文件中读取值。对于实体框架连接,这意味着您必须将连接信息复制到应用程序的 app.config 中。
The DLL doesn't have its own app.config at runtime. The app.config is only there for the Entity Framework designer.
During execution, the DLL will try to read the values from the Application's app.config file. For Entity Framework connections, that means you have to copy the connection information into the Application's app.config.
.NET 最多只会为正在执行的程序集加载一个 App.config 文件。如果您的附属程序集具有 App.config 文件,则执行程序集不会解析它们。
为了从附属程序集的 App.config 获取设置,您必须将这些设置移动(复制)到执行程序集的 App.config 中。
.NET will only load at most one App.config file for an executing assembly. If your satellite assemblies have App.config files, they will not be parsed by the executing assembly.
In order to get the settings from the satellite assembly's App.config you must move (copy) those settings into your executing assembly's App.config.
我是这样解决的。假设 .config 文件中包含连接字符串的程序集是项目中的引用,因此与正在执行的程序集一起存在。
I solved it like this. Assuming your assembly with the connection string in it's .config file is a reference in your project and so exists along side the executing assembly.