RJN
RJN

Reputation: 736

Unable to read App.config from DLL

I have moved App.config file which contains some AppSettings into DLL project from the EXE project of same solution. After that I have noticed using Configuration manager, I get only null values.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
    <add key="Path1" value="C:\ProgramData\Resources\file2.xml" />
    <add key="Path2" value="C:\ProgramData\Development\file1.xml" />
</appSettings>
</configuration>

/* Reading */
public string Path1=> ConfigurationManager.AppSettings["Path1"];
public string Path2=> ConfigurationManager.AppSettings["Path2"];

If I move back the App.config into my EXE project, I'm able to read all values right using configuration manager.

So, my question is if I have only DLL (COM) project in my solution where I dont have control on EXE(developed by 3rd party) project then how to manage the settings using App.config file?

Upvotes: 0

Views: 3433

Answers (2)

rk.
rk.

Reputation: 11

You shouldn't be using app.config for any settings in class library. It's bad practice to do so and that is the reason even Microsoft doesn't provide app.config in class library.

Any value required by class library should be passed to the class from application using parameters. For instance, in your case file path can be passed as parameter to your class method or constructor etc.

But if you still want to access try this options
1. Add reference to System.Configuration.dll to your class library and add using System.Configuration in using block
2. Write code to read app.config file as normal xml file. Somewhat like this.

   string getFilePath()
   {
    string path = Path.GetDirectoryName(Assembly.GetCallingAssembly().CodeBase) + @"\ClassLibrary.dll.config";

    XDocument doc = XDocument.Load(path);

    var query = doc.Descendants("appSettings").Nodes().Cast<XElement>().Where(x => x.Attribute("key").Value.ToString() == key).FirstOrDefault();

    if (query != null)
    {
        return query.Attribute("value").Value.ToString();
    }

Upvotes: 1

Chad
Chad

Reputation: 1562

Config files do not get compiled into the dll.

The app will use the app.config from the startup project of your solution unless you put in special code to look elsewhere.

This is by design so that you can change configuration with out having to recompile just because a setting changed.

Upvotes: 3

Related Questions