Is there any difference between Server.MapPath() and HostingEnvironment.MapPath()? Does Server.MapPath() have any advantages over HostingEnvironment.MapPath()?
My original problem was mapping the file path on a server when the HttpContext is not present and I cannot pass a Server variable from Global.asax to my method.
I used HostingEnvironment.MapPath() instead since it doesn’t need HttpContext. Are there any situations when these two methods will give different results?
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
Server.MapPath() eventually calls HostingEnvironment.MapPath(), but it creates a VirtualPath object with specific options:
The
VirtualPathobject passed toHostingEnvironment.MapPath()is constructed like this:VirtualPath.Create(path, VirtualPathOptions.AllowAllPath|VirtualPathOptions.AllowNull);
Edit: in reality, the only difference is that you are allowed to pass null to Server.MapPath(), but not to HostingEnvironment.MapPath()
Method 2
Server.MapPath() requires an HttpContext. HostingEnvironment.MapPath does not.
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