Alex
Alex

Reputation: 77329

Get current application physical path within Application_Start

I'm not able to get the current physical path within Application_Start using

HttpContext.Current.Request.PhysicalApplicationPath

because there is no Request object at that time.

How else can I get the physical path?

Upvotes: 46

Views: 162380

Answers (10)

Manoochehr Dadashi
Manoochehr Dadashi

Reputation: 726

Best choice is using

AppDomain.CurrentDomain.BaseDirectory

because it's in the system namespace and there is no dependency to system.web

this way your code will be more portable

Upvotes: 5

batressc
batressc

Reputation: 1588

I created a website with ASP.Net WebForms where you can see the result of using all forms mentioned in previous responses from a site in Azure.

http://wfserverpaths.azurewebsites.net/

Summary:


Server.MapPath("/") => D:\home\site\wwwroot\

Server.MapPath("~") => D:\home\site\wwwroot\

HttpRuntime.AppDomainAppPath => D:\home\site\wwwroot\

HttpRuntime.AppDomainAppVirtualPath => /

AppDomain.CurrentDomain.BaseDirectory => D:\home\site\wwwroot\

HostingEnvironment.MapPath("/") => D:\home\site\wwwroot\

HostingEnvironment.MapPath("~") => D:\home\site\wwwroot\

Upvotes: 33

TJF
TJF

Reputation: 2258

Use Server.MapPath("~")

   

Upvotes: 17

Jenna Leaf
Jenna Leaf

Reputation: 2452

There's, however, slight difference among all these options which

I found out that

If you do

    string URL = Server.MapPath("~");

or

    string URL = Server.MapPath("/");

or

    string URL = HttpRuntime.AppDomainAppPath;

your URL will display resources in your link like this:

    "file:///d:/InetPUB/HOME/Index/bin/Resources/HandlerDoc.htm"

But if you want your URL to show only virtual path not the resources location, you should do

    string URL = HttpRuntime.AppDomainAppVirtualPath; 

then, your URL is displaying a virtual path to your resources as below

    "http://HOME/Index/bin/Resources/HandlerDoc.htm"        

Upvotes: 1

maxy
maxy

Reputation: 438

use below code

server.mappath() in asp.net

application.startuppath in c# windows application

Upvotes: 3

hakan
hakan

Reputation: 3534

System.AppDomain.CurrentDomain.BaseDirectory

This will give you the running directory of your application. This even works for web applications. Afterwards, you can reach your file.

Upvotes: 2

rick schott
rick schott

Reputation: 20617

 protected void Application_Start(object sender, EventArgs e)
 {
     string path = Server.MapPath("/");
     //or 
     string path2 = Server.MapPath("~");
     //depends on your application needs

 }

Upvotes: 53

senthilkumar2185
senthilkumar2185

Reputation: 2566

You can use this code:

AppDomain.CurrentDomain.BaseDirectory

Upvotes: 10

DotNetUser
DotNetUser

Reputation: 6612

You can also use

HttpRuntime.AppDomainAppVirtualPath

Upvotes: 23

Alex
Alex

Reputation: 741

There is also the static HostingEnvironment.MapPath

Upvotes: 3

Related Questions