187

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?

George Stocker
  • 56,270
  • 29
  • 173
  • 234
empi
  • 15,465
  • 8
  • 60
  • 76
  • Related post - [Server.MapPath("."), Server.MapPath("~"), Server.MapPath(@"\"), Server.MapPath("/"). What is the difference?](https://stackoverflow.com/q/275781/465053) – RBT Sep 20 '21 at 04:44

2 Answers2

218

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()

shA.t
  • 15,880
  • 5
  • 49
  • 104
Philippe Leybaert
  • 162,851
  • 30
  • 206
  • 220
  • 2
    So I will always get same results from both methods, right? (excluding null argument) – empi Jun 03 '09 at 11:52
  • 65
    **TL;DR**: always use `HostingEnvironment.MapPath()` to keep sanity. (+1) – Chris Marisic Jun 01 '12 at 20:23
  • 17
    There must be something different beyond null because `Server.MapPath("myFolder")` works fine but to get the same result with HostingEnvironment, I had to use `HostingEnvironment.MapPath("~/myFolder")`. – styfle Nov 14 '12 at 23:54
  • Fantastic answer for initiating an ftp session via a call to a web service. Saved me huge today!!! – htm11h Mar 05 '14 at 15:54
  • 10
    Actually there is another difference - relative paths (e.g. Image/pict.png) are not allowed with HostingEnvironment.MapPath. – NetMage Sep 04 '14 at 22:25
118

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

George Stocker
  • 56,270
  • 29
  • 173
  • 234
Mark Struzinski
  • 32,365
  • 34
  • 104
  • 135