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

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.

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();

You can use the ConfigurationManager class to open the configuration file of another executable.
Configuration conf = ConfigurationManager.OpenExeConfiguration(exeFilePath);
// edit configuration settings
conf.Save();

See ConfigurationManager.OpenExeConfiguration

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.

ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = Environment.CurrentDirectory + "\\MyApp.exe.config";
//i have config in the same directory as my another app
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
var settingsSection = (System.Configuration.ClientSettingsSection)config.GetSection("userSettings/MyApp.Properties.Settings");
var setting = settingsSection.Settings.Get("MySetting");
var param = ((setting.Value.ValueXml).LastChild).InnerText.ToString();

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;

Related

How to Set the Configuration File to current dll.config

When I start my exe , the configuration file is set to mypp.exe.config.
After certian point , I want it to point to mydll.config.
I am trying with:
var configPath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
var Location = Assembly.GetExecutingAssembly().Location;
AppDomain.CurrentDomain.SetupInformation.ConfigurationFile = config.FilePath;
But when I set a break point to see, the Configuration file is still set to myapp.exe.config.
What's missing?
Use AppDomain.SetData:
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", config.FilePath);
I can't find any documentation for that, but it worked for me.

How to programatically read the xx.exe.confg file of another application

I am trying to read the app settings in the config file of another application (app.exe.config).
I have tried several things. Most recently I used this:
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(FullPath() + ".config");
// Get the AppSetins section.
AppSettingsSection appSettingSection = config.AppSettings;
// Display raw xml.
Debug.WriteLine(appSettingSection.SectionInformation.GetRawXml());
but the GetRawXml() returns nothing. Where am I going wrong? The FullPath() method returns the correct path, I have tested this.
M
Config files are valid xml files so you can also try using XElement.Load(filepath) and process the xml tree as desired.
var appSettingsRawXml = System.Xml.Linq.XElement.Load(FullPath() + ".config")
.Element("appSettings")
.ToString();
GetRawXml supports the .NET Framework infrastructure and is not intended to be used directly from your code. MSDN

Read config files in a WPF project

I have a WPF application. This application should read a web.config file (from a asp.net webforms project) and a myCompany.config file.
How can I do this? Is there a easy way to handle this?
Any help would be appreciated.
thanks!
Sounds like you need to use configurationmanager
http://msdn.microsoft.com/en-us/library/aa719887%28v=vs.71%29.aspx
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx
So if I understood correctly, you want to read config files which are stored in a specific path?
Here is the trick:
Configuration _userConfig;
String configFilePath = "Your path here";
//Getting the user configuration object:
//Mapping the appropriate path:
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = configFilePath;
_userConfig = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
And there you go, _userConfig will contain the details in the path you specified :)

How can I properly reference this config file so I'm not hard coding the path?

Im trying to reference this config file that is in the same folder as the class that contains this code. I'd like to do some type of relative reference to it, so I can use it from other places. When I try using just the file name without the path, the application doesn't find the file. I debugged and the folder it seems to be looking in IIS folder which makes sense as Im using it in an IIS hosted wcf service. Anyways, how I can properly reference this config file without hard coding the path? So it looks in the project location. Thanks for any help. Have a great weekend!
public void Init()
{
var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = #"C:\workspace\new\UnityDemo-v1.0.0.1\src\Core\unity.config" };
Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
var unitySection = (UnityConfigurationSection)configuration.GetSection("unity");
_container = new UnityContainer().LoadConfiguration(unitySection);
}
Cheers,
~ck
Using config files with services hosted in IIS is tricky, because the application directory is the one IIS runs in and that will be heavily protected against placing any files there. There may be other ways but for me it works to name the file web.config and copy it to the directory the .svc file resides in and then you can read the settings directly without having to reference the config file. I do not know of any way to do this copying from within the program itself. The installer will be able to do it though.
See: this question
Use Application.StartupPath to get the path the application started in then simply combine with the filename to get the full path:
var filePath = Path.Combine(Application.StartupPath, "unity.config");
var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = filePath };
This will work only in winforms.
Another option is to use Environment.CurrentDirectory - by default it will be set to the process startup directory. Note that this property is mutable:
var filePath = Path.Combine(Environment.CurrentDirectory, "unity.config");
var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = filePath };
Another option that worked for me in .NET is using Server.MapPath. This returns the full path of the given relative virtual path in the web application.
var filePath = Server.MapPath("/unity.config")
This physical file path can then be used to create the file map as above.

ConfigurationManager.OpenExeConfiguration - loads the wrong file?

I have added multiple app.config (each with a differet name) files to a project, and set them to copy to the output directory on each build.
I try and access the contents of each file using this:
System.Configuration.Configuration o = ConfigurationManager.OpenExeConfiguration(#"app1.config");
The code runs, but o.HasFile ends up False, and o.FilePath ends up "app1.config.config". If I change to code:
System.Configuration.Configuration o = ConfigurationManager.OpenExeConfiguration(#"app1");
Then the code bombs with "An error occurred loading a configuration file: The parameter 'exePath' is invalid. Parameter name: exePath".
If I copy/paste the config file (so I end up with app1.config and app1.config.config) then the code runs fine, however, I posit this is not a good solution. My question is thus: how can I use ConfigurationManager.OpenExeConfiguration to load a config file corretly?
I can't remember where I found this solution but here is how I managed to load a specific exe configuration file:
ExeConfigurationFileMap map = new ExeConfigurationFileMap { ExeConfigFilename = "EXECONFIG_PATH" };
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
According to http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/3943ec30-8be5-4f12-9667-3b812f711fc9 the parameter is the location of an exe, and the method then looks for the config corresponding to that exe (I guess the parameter name of exePath makes sense now!).
To avoid this problem altogether, you can read in the config file as an XML file, for example:
using System.Xml;
using System.Xml.XPath;
XmlDocument doc = new XmlDocument();
doc.Load(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\..\\..\\..\\MyWebProject\\web.config");
string value = doc.DocumentElement.SelectSingleNode("/configuration/appSettings/add[#key='MyKeyName']").Attributes["value"].Value;
using System.Reflection;
try
{
Uri UriAssemblyFolder = new Uri(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase));
string appPath = UriAssemblyFolder.LocalPath;
//Open the configuration file and retrieve
//the connectionStrings section.
Configuration config = ConfigurationManager.
OpenExeConfiguration(appPath + #"\" + exeConfigName);
ConnectionStringsSection section =
config.GetSection("connectionStrings")
as ConnectionStringsSection;
}
At least, this is the method I use when encrypting and decrypting the connectionStrings section for my console/GUI apps. exeConfigName is the name of the executable including the .exe.

Categories

Resources