Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read user settings in app.config from a diff app?

Tags:

c#

winforms

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.

like image 256
etoisarobot Avatar asked Feb 27 '23 23:02

etoisarobot


2 Answers

this should do it :

var clientSettingsSection = (System.Configuration.ClientSettingsSection)(ConfigurationManager.GetSection("userSettings/YourApplicationName.Properties.Settings"));
var setting = clientSettingsSection.Settings.Get("yourParamName_DB_");
string yourParamName_DB = ((setting.Value.ValueXml).LastChild).InnerText.ToString();
like image 194
M0-3E Avatar answered Mar 16 '23 08:03

M0-3E


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

Configuration conf = ConfigurationManager.OpenExeConfiguration(exeFilePath);
// edit configuration settings
conf.Save();
like image 38
Pop Catalin Avatar answered Mar 16 '23 07:03

Pop Catalin