BrunoLM
BrunoLM

Reputation: 100381

How to read app.config from another assembly?

I have two projects:

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 ?

Upvotes: 17

Views: 11538

Answers (4)

Naveen Dwivedi
Naveen Dwivedi

Reputation: 1

 string value = ConfigurationManager.OpenExeConfiguration(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "yourassembly.dll"))?.AppSettings.Settings["yourAppconfigKey"].Value ?? "";

Upvotes: 0

NitrusCS
NitrusCS

Reputation: 763

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;

Upvotes: 1

Nathan Taylor
Nathan Taylor

Reputation: 24606

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

Upvotes: 7

Justin Niessner
Justin Niessner

Reputation: 245479

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.

Upvotes: 12

Related Questions