.NET Framework - Using ConfigurationManager to modify another project's app.config

Asked By Jeff on 14-May-08 12:49 AM
I have a solution with two projects.  Project A is the startup
project, while Project B serves as the project with the data logic.

At run time, the first thing I need to do is write to Project B's
app.config.  I've referenced System.configuration.dll within Project
B, and from one of the classes inside Project B's namespace, I'm
trying to use ConfigurationManager to write to its app.config.
Unfortunately, it only finds Project A's app.config.  I've even tried
removing Project A's app.config file, but it still can't "see" Project
B's app.config.

Is there any way to accomplish this?




jwin replied on 13-May-08 08:09 PM
The reason you cannot see the other project's app.config directly from
ConfigurationManager is because when the appdomain is loaded the (i would
imagine) .net framework decides which configuration file that application
should use.

You can access other application configuration files by opening them
directly and then accessing the information in them using the configuration
manager class.

using System.Configuration;

string path = "C:\\MyExecutable.exe"; // The path must be that of your
executable, not the path of the config file.
Configuration config = ConfigurationManager.OpenExeConfiguration(path);

Once the file has been opened, you'll be able to modify it similarly to how
you would normally access the data. Once you're done accessing it just call
the config.Save(); method or the appropriate overload your application
requires. Keep in mind, modifying an application's config file while it's
running will not change the configuration that gets cached once the
ConfigurationManager has been used.

Meaning: if you start project A, and then start project B - use the
ConfigurationManager in project B to access some data in it, and then have
project A modify the configuration for project B - project B's configuration
will not update until the appdomain is reloaded.

HTH,
- Jeff
Peter Bromberg [C# MVP] replied on 13-May-08 10:57 PM
If you have a solution with an executable that references some class library
that is in another project in the solution, consider keeping all your
configuration information in the config file for the executable project.
Code in your class library will be able to "see" all the configuration data
from the main program. Keep it simple.
Peter