How to read app.config from another assembly?
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="me开发者_高级运维tadata=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
?
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 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.
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.
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;
精彩评论