Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenExeConfiguration Path Issue

I'm trying to load an web.config from a server. Its placed at: \server\folders\web.config

when i try this:

 ConfigurationManager.OpenExeConfiguration(@"\\server\folders\web.config");

it searches for: web.config.config and fails.

 ConfigurationManager.OpenExeConfiguration(@"\\server\folders\web");

it fails, because there is no folder \server\folders\web\

So i tried several things and it seems as its checking wether the file the path is pointing on exists, and afterwards it appliers a .config and gets the config file.

Just for fun i created an web.loaders file, and a web.loaders.config file. with

 ConfigurationManager.OpenExeConfiguration(@"\\server\folders\web.local");

it loads the \server\folders\web.local.config perfectly, but throws Exceptions without the web.local file.

So there a many ways to get this small thing loaded, but isn't there a more nice one than using a temp .web file or something?

like image 597
Harry Avatar asked May 09 '26 15:05

Harry


2 Answers

ConfigurationManager.OpenExeConfiguration is intended for loading the configuration for an executable and so really expects the full path to an .exe file. The config file is expected to be in the same directory as the .exe and have the extension .exe.config, so it isn't really suitable for loading the configuration of an ASP.NET website. A better choice is to use the WebConfigurationManager. The OpenWebConfiguration method is okay if you're opening the config from within the site since it expects the virtual path to the config, but if you're opening it from something like a console app then you'll need to look at the OpenMappedWebConfiguration method. The documentation gives an example how you might achieve this.

There's also a previous question and answer on Stack Overflow showing how to do this.

like image 86
Steve Rowbotham Avatar answered May 11 '26 03:05

Steve Rowbotham


You need to map the virtual path to a physical path first.

string configPath = HttpContext.Current.Server.MapPath("~/server/folders/web.local");      
ConfigurationManager.OpenExeConfiguration(configPath);

The ~ at the start of the virtual path goes to the root of your application. If you are referencing a relative file from your page, you may not want to use it.

like image 44
Geoff Cox Avatar answered May 11 '26 05:05

Geoff Cox