views:

1496

answers:

4

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

+14  A: 

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

No HttpContext required.

Corbin March
Perfect! Thanks!
SkippyFire
Any caveats to this technique?
SkippyFire
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
A: 

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

Terry
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.
SkippyFire
A: 

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
A: 

Use AppDomain.CurrentDomain.BaseDirectory :-) because Context might return null !!

Cheers, Kiran Banda

Kiran Banda