I need to use Server.MapPath() to combine some files path that I store in the web.config.
However, since Server.MapPath() relies on the current HttpContext (I think), I am unable to do this. When trying to use the method, even though its “available”, I get the following exception:
Server operation is not available in this context.
Is there another method that can map a web root relative directory such as ~/App_Data/ to the full physical path such as C:inetpubwwwrootprojectApp_data ?
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
You could try System.Web.Hosting.HostingEnvironment.MapPath().
No HttpContext required.
Method 2
Use AppDomain.CurrentDomain.BaseDirectory because Context might return null !!
Method 3
When in Global.asax, use the context object:
context.Server.mappath()
Context lets you access also the session collection, the request object, the response object. Very useful when you want to log errors, for example
Method 4
You could try HttpContext.Current.Server.MapPath(“/”) – That’s how I have referenced it before in classes.
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