Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing App.config in a location different from the binary

Tags:

c#

In a .NET Win console application, I would like to access an App.config file in a location different from the console application binary. For example, how can C:\bin\Text.exe get its settings from C:\Test.exe.config?

like image 362
Chris Comeaux Avatar asked Sep 16 '08 19:09

Chris Comeaux


3 Answers

using System.Configuration;    

Configuration config =
ConfigurationManager.OpenExeConfiguration("C:\Test.exe");

You can then access the app settings, connection strings, etc from the config instance. This assumes of course that the config file is properly formatted and your app has read access to the directory. Notice the path is not "C:\Test.exe.config" The method looks for a config file associated with the file you specify. If you specify "C:\Test.exe.config" it will look for "C:\Test.exe.config.config" Kinda lame, but understandable, I guess.

Reference here: http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openexeconfiguration.aspx

like image 170
jeff.willis Avatar answered Nov 16 '22 02:11

jeff.willis


It appears that you can use the AppDomain.SetData method to achieve this. The documentation states:

You cannot insert or modify system entries with this method.

Regardless, doing so does appear to work. The documentation for the AppDomain.GetData method lists the system entries available, of interest is the "APP_CONFIG_FILE" entry.

If we set the "APP_CONFIG_FILE" before any application settings are used, we can modify where the app.config is loaded from. For example:

public class Program
{
    public static void Main()
    {
        AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", @"C:\Temp\test.config");
        //...
    }
}

I found this solution documented in this blog and a more complete answer (to a related question) can be found here.

like image 8
CodeNaked Avatar answered Nov 16 '22 03:11

CodeNaked


Use the following (remember to include System.Configuration assembly)

ConfigurationManager.OpenExeConfiguration(exePath)
like image 6
Santiago Palladino Avatar answered Nov 16 '22 03:11

Santiago Palladino