How can I use Server.MapPath() from global.asax?
Asked Answered
T

4

131

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\ ?

Thisbe answered 1/6, 2009 at 17:57 Comment(0)
P
312

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

No HttpContext required.

Petry answered 1/6, 2009 at 18:5 Comment(3)
Any caveats to this technique?Thisbe
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.Petry
+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.Sestet
P
5

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

Photogram answered 2/2, 2010 at 8:32 Comment(0)
U
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

Unhandled answered 1/6, 2009 at 22:12 Comment(1)
There is no guaranteed Context in Global.asax.Ciri
A
-5

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

Apetalous answered 1/6, 2009 at 18:8 Comment(1)
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.Thisbe

© 2022 - 2024 — McMap. All rights reserved.