Eric Anastas
Eric Anastas

Reputation: 22233

How can I make a DLL ApplicationSettings class which reads from library.dll.config?

I'm creating a plug-in for another application as a DLL, which needs to have settings that can be configured without recompiling the DLL. I created a settings class through Visual Studio as I usually do with application projects. When I build my project a libraryname.dll.config file is created and copied to the output directly.

But, as may other people have already found and written about, this file is never used. Instead if I want to modify these DLL settings I need to merge the settings into the settings file for whatever application that is using the DLL.

The problem I have with this is the calling application is not my application, so I'd rather the configuration of my plug-in live with the rest of my files for my plug-in.

In the past I've used System.Configuration.ConfigurationManager.OpenExeConfiguration() to read a settings file for the DLL like this.

    public static string GetSettingValue(string key)
    {
        string assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
        var config = ConfigurationManager.OpenExeConfiguration(assemblyPath);
        var keyVal = config.AppSettings.Settings[key]
        return keyVal.Value;
    }

Which would read from a settings file like this

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="URL" value="http://www.acme.com" />
    <add key="EnableAdmin" value="False" />
  </appSettings>
</configuration>

However, I really like newer type safe ApplicationSettings class that is created by visual studio rather then then using <appSettings> which can only store strings.

So what I'm wondering is if there is some way I could override a method or two in the ApplicationSettings class created by visual studio to get it to read from the DLL config file by default? It's not really clear to me exactly where it's being determined which config file should be read.

Upvotes: 2

Views: 2658

Answers (2)

Landers74
Landers74

Reputation: 11

You can try to merge the applicationsettings file in the calling application. This SO thread explains it pretty well.

How to load a separate Application Settings file dynamically and merge with current settings?

If you do not want to mess with editing the calling application, you can just use the Configuration class like you are doing. Here's another example. I've used this approach when I needed to call a WCF service through COM.

http://www.twisted-bits.com/2012/04/use-a-net-configuration-file-with-a-class-library-dll/

Upvotes: 1

robrich
robrich

Reputation: 13205

Copy the applicable section to the web.config of the main site or app.config of the main executable, then ConfigurationManager.AppSettings["URL"] works just fine.

Upvotes: 0

Related Questions