What is the difference between Server.MapPath and HostingEnvironment.MapPath?

C#asp.net

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

Server.MapPath() eventually calls HostingEnvironment.MapPath(), but it creates a VirtualPath object with specific options:

> The VirtualPath object passed to HostingEnvironment.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()

Solution 2 - C#

Server.MapPath() requires an HttpContext. HostingEnvironment.MapPath does not.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionempiView Question on Stackoverflow
Solution 1 - C#Philippe LeybaertView Answer on Stackoverflow
Solution 2 - C#Mark StruzinskiView Answer on Stackoverflow