OK so we have something that is currently using OpenExeConfiguration for reading a config file, however this doesn't work when running in the web context.
I've tried a variety of different ways of opening the web.config programmatically but I can't seem to get it to read the correct web.config file. In case it matters I am currently debugging it in VS 2008.
1. config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(System.Web.HttpContext.Current.Request.ApplicationPath); 2. config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = "web.config" }, ConfigurationUserLevel.None); 3. config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); 4. config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null); 5. System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
It either opens up the wrong config file (either the machine config, or the VS /IDE/Web.config) or complains about the error:
{System.Configuration.ConfigurationErrorsException: An error occurred loading a configuration file: Failed to map the path '/'. ---> System.InvalidOperationException: Failed to map the path '/'.
Edit - OK so a combination of
config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
AND running Visual Studio 2008 As Administrator worked. Am hoping we don't run into security/permission issues when we deploy to our web server / client environments!
So in the end I used this code (had to handle whether the web application was running, or if our unit test code was running).
System.Configuration.Configuration config = null; if (System.Web.HttpContext.Current != null && !System.Web.HttpContext.Current.Request.PhysicalPath.Equals(string.Empty)) config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); else config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Also have to be running Visual Studio in Administrator mode - which I found out you can set as a property on your shortcut so you don't need to remember each time in Windows 7 to right click and run as administrator :)
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