130

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:\inetpub\wwwroot\project\App_data\ ?

AlexB
  • 7,302
  • 12
  • 56
  • 74
John B
  • 20,062
  • 35
  • 120
  • 170

4 Answers4

312

You could try System.Web.Hosting.HostingEnvironment.MapPath().

No HttpContext required.

Corbin March
  • 25,526
  • 6
  • 73
  • 100
  • Any caveats to this technique? – John B Jun 03 '09 at 15:00
  • 11
    Nope. If you fire up Reflector, you'll notice that Server.MapPath and Request.MapPath ultimately call VirtualPath.MapPath which ultimately calls HostingEnvironment.MapPath. They all end up in the same place. HostingEnvironment.MapPath cuts out the middle man. – Corbin March Jun 03 '09 at 17:44
  • 1
    +1 this fixed an open source project that was working for me then just stopped initializing due to HttpContext.Current.Server blowing up for it not having a context for some reason. Switching to this put it back to smooth sailing. – Chris Marisic Mar 04 '11 at 14:18
5

Use AppDomain.CurrentDomain.BaseDirectory because Context might return null !!

A--C
  • 36,351
  • 10
  • 106
  • 92
Kiran Banda
  • 59
  • 1
  • 1
1

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

tekBlues
  • 5,745
  • 1
  • 29
  • 32
-5

You could try HttpContext.Current.Server.MapPath("/") - That's how I have referenced it before in classes.

VoltaicShock
  • 842
  • 2
  • 7
  • 19
  • 2
    You can reference it like that in classes that actually HAVE an HttpContext, but I don't think global.asax has one, hence the error message I received. – John B Jun 01 '09 at 18:16