How to replace OpenExeConfiguration in a web context (asp.net mvc 1)

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!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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 🙂


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x