16

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=&quot;{0}&quot;" 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 ?

BrunoLM
  • 97,872
  • 84
  • 296
  • 452
  • The correct answer ist given here. It works http://stackoverflow.com/questions/53545/get-the-app-config-of-another-exe –  Jan 12 '12 at 11:29

3 Answers3

12

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.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
7

.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.

Nathan Taylor
  • 24,423
  • 19
  • 99
  • 156
1

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;
NitrusCS
  • 597
  • 1
  • 5
  • 20