directedition
directedition

Reputation: 11705

Use ConfigurationManager with custom path to config file

I see many solutions to reading in values from an external configuration file in a C# console application, but I can't find a solution for my particular circumstances:

  1. Due to reasons of deployment (mainly that this is for a console application that is packed for deployment as part of an MVC website using the Visual Studio web Publish method), the exe does not get packaged with its app.config file.

  2. I'm dependent on libraries that make use of the ConfigurationManager.AppConfig["blah"] syntax, and I can't very well pass in my own AppSettingsSection to these libs.

My console application's .exe file is in the MVC app's bin directory. As both the website and the console app use the same config values, I was trying to simply load the site's Web.config file into the console app, but I haven't found a way of doing this.

Upvotes: 1

Views: 2254

Answers (1)

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64933

The default configuration file is loaded once the AppDomain is loaded. For console applications, the configuration file must be located in the same place as the executable.

I believe that one possible solution is loading an AppDomain as a child of the console application and setting up the AppDomainSetup.ConfigurationFile property rightly to load the configuration file from the custom location, and then execute the whole console application's logic inside the child AppDomain.

You can use this AppDomain.CreateDomain overload for this case (the MSDN article contains a sample code on how to provide the AppDomainSetup):

As far as I know, you can't change the default behavior of where the executable AppDomain looks for the configuration file once it's loaded, but as I suggested you, you can create your own AppDomain with your own requirements!

Upvotes: 1

Related Questions