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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With