Using ConfigurationManager to modify another project's app.config

J

Jeff

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?
 
J

jwinn

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
 
P

Peter Bromberg [C# MVP]

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
 
P

PRATAP singh

Hi,
i tried the way that u guided but it pops this build error:

Error 'System.Configuration.ConfigurationElement.this[System.Configurat
ion.ConfigurationProperty]' is inaccessible due to its protection level

how can i change the protection level of config file to resolve the
issue?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top