How can I get ConfigurationManager to load application settings from multiple files?

Robert Rossney picture Robert Rossney · Jul 28, 2009 · Viewed 8.8k times · Source

I'm writing applications that interoperate with a third-party application. This application exposes an API to developers via methods in a DLL. Some time ago, the vendor of this app started integrating their own .NET components into their program, and when they did, they decided that their components should use the ConfigurationManager to get settings at runtime.

What this means: their program, foo.exe, calls fooengine.dll, and it reads its settings from foo.exe.config. My program, bar.exe, also calls fooengine.dll, and it reads its settings from bar.exe.config.

Well, that's just plain wrong. But how do I fix it?

The simple workaround is to replicate foo.exe.config's settings in bar.exe.config. That'll work, but it's stupid. It means that from an administrative standpoint, a given setting has to be maintained in N different files. That's going to fail sooner or later.

I tried putting a configSource attribute on the appSettings section in my config file. (As it happens, I'm using the applicationSettings section for my settings, and they're using the appSettings section for theirs, so I can live with simply getting that section from a different file.) But the ConfigurationManager doesn't like that: it wants the path in configSource to be not only relative to but below my program's directory.

I can physically read their settings file into an XmlDocument and then set them myself. But now I'm tightly coupling my code to their implementation; if they put out a new release that moves the settings to the applicationSettings section (which is where they should be now that it's 2009), my code will break.

Is there another way out of this?

Answer

Robert Rossney picture Robert Rossney · Jul 28, 2009

Okay, I think I've found the answer, at least for my specific version of this problem.

The .NET 2.0 ConfigurationManager supports a file attribute on the appSettings element. This lets you get the contents of that element from an external file. So what I do is:

  1. Cut the appSettings element out of foo.exe.config and paste it into another file in that directory called, let's say, appSettings.xml.

  2. Add a new element to foo.exe.config: <appSettings file="appSettings.xml"/>.

  3. Add an element to bar.exe.config: <appSettings file="c:\program files\foo\appSettings.xml"/>

This works. But it only works because my program doesn't use appSettings at all.