tags:

views:

468

answers:

4

I have a WinForms .exe with an App.config that has a bunch of User Scoped Settings that are set at runtime and saved. I want to be able to use the WinForms app to change and save the settings and then click on button to do some work based on the those settings. I also want to read the user settings in the same .config file from a sep. console app so I can schedule to work to be done as a scheduled task. What is the best way to be able to do this?

Update: I tried the reccommendation of using ConfigurationManager.OpenExeConfiguration as described in some of the answers like so.

Configuration config = ConfigurationManager.OpenExeConfiguration("F:\\Dir\\App.exe");

but when I try to retrieve a User Setting like so.

string result = config.AppSettings.Settings["DB"].ToString();

I get a Null reference error.

From code in the exe however the following correctly returns the DB name.

Properties.Settings.Default.DB

Where am I going wrong?

Update 2:

So based on some of the answers below I now can use the following to retrieve the raw XML of the section of the user.config file I am interested in from sep. ConsoleApp.

System.Configuration.ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = @"D:\PathHere\user.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap,ConfigurationUserLevel.None);
System.Configuration.DefaultSection configSection = (System.Configuration.DefaultSection)config.GetSection("userSettings");
string result = configSection.SectionInformation.GetRawXml();
Console.WriteLine(result);

But I am still unable to just pull the value for the specific element I am interested in.

A: 

If you know the path to the config file try:

System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration("configPath");

string myValue = config.AppSettings.Settings[ "myValue" ].Value;

Jay
A: 

See ConfigurationManager.OpenExeConfiguration

Captain Comic
+1  A: 

You can use the ConfigurationManager class to open the configuration file of another executable.

Configuration conf = ConfigurationManager.OpenExeConfiguration(exeFilePath);
// edit configuration settings
conf.Save();
Pop Catalin
A: 

If you are setting these values per user basis you may need to use the ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel) method instead of the current method you are using now.