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

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("~")

Another possibility is AppDomain.CurrentDomain.BaseDirectory

Some additional ways: Different ways of getting Path


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);

Tags:

Asp.Net