How do I get the root directory of my ASP.NET server application?

asp.net

asp.net Problem Overview


In the start-up code (ie no request) of my ASP.NET application I need to get the path to the root of my app. I need this to open a file I have in a folder off the root directory.

How can I get this?

asp.net Solutions


Solution 1 - asp.net

Server.MapPath("~"); 

Will get you the root directory of the current application, as a path on the disk. E.g., C:\inetpub\...

Note that the ~ character can be used as part of web paths in ASP.NET controls as well, it'll fill in the URL to your application.

If your class doesn't have Server property, you can use static

HttpContext.Current.Server.MapPath("~")

Solution 2 - asp.net

HttpRuntime.AppDomainAppPath is useful if you don't have a HttpContext available.

For example, a low-level library method to get a path relative to the current application, and it has to work whether it is a web app or not:

private static string GetDataFilePath() => HttpRuntime.AppDomainAppVirtualPath != null ?
    Path.Combine(HttpRuntime.AppDomainAppPath, "App_Data") :
    Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

Solution 3 - asp.net

Another possibility is AppDomain.CurrentDomain.BaseDirectory

Some additional ways: Different ways of getting Path

Solution 4 - asp.net

You can get this from Server.MapPath method.

Here is the MSDN Link: http://msdn.microsoft.com/en-us/library/ms524632(v=vs.90).aspx

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
QuestionDavid ThielenView Question on Stackoverflow
Solution 1 - asp.netdebraceyView Answer on Stackoverflow
Solution 2 - asp.netChristian HayterView Answer on Stackoverflow
Solution 3 - asp.netChristoph WissingView Answer on Stackoverflow
Solution 4 - asp.netTK1View Answer on Stackoverflow