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

C#asp.netGlobal Asaxserver.mappathApplication Start

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

No HttpContext required.

Solution 2 - C#

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

Solution 3 - C#

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

Solution 4 - C#

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

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
QuestionJohn BView Question on Stackoverflow
Solution 1 - C#Corbin MarchView Answer on Stackoverflow
Solution 2 - C#Kiran BandaView Answer on Stackoverflow
Solution 3 - C#tekBluesView Answer on Stackoverflow
Solution 4 - C#VoltaicShockView Answer on Stackoverflow