58

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?

David Thielen
  • 28,723
  • 34
  • 119
  • 193

4 Answers4

96
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("~")
Michael Freidgeim
  • 26,542
  • 16
  • 152
  • 170
debracey
  • 6,517
  • 1
  • 30
  • 56
  • 4
    This caused a `NullReferenceException` as described [here](https://stackoverflow.com/q/6861368/197591). I think `HttpRuntime.AppDomainAppPath` is preferable as per [here](https://stackoverflow.com/a/6861451/197591) and [here](https://stackoverflow.com/a/3549729/197591) (read comments and go to the [link](https://stackoverflow.com/q/3025984/197591)). – Neo Sep 30 '19 at 10:00
  • I get "Server operation is not available in this context" when I try this. – Ristogod Mar 22 '22 at 21:36
45

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);
Christian Hayter
  • 30,581
  • 6
  • 72
  • 99
  • 4
    This is very useful when you cannot use HttpContext to get the Server object – Sam Nov 12 '15 at 15:48
  • 4
    This method returned what I was looking for: The root URL of my application running in IIS. Server.MapPath returns a file directory. – Chris - Haddox Technologies Jan 10 '18 at 15:47
  • for efficiency change it to a static variable: `private static string DataFilePath = HttpRuntime.AppDomainAppVirtualPath != null ? Path.Combine(HttpRuntime.AppDomainAppPath, "App_Data") : Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);` – dovid Sep 15 '20 at 10:31
7

Another possibility is AppDomain.CurrentDomain.BaseDirectory

Some additional ways: Different ways of getting Path

Chris Nielsen
  • 14,731
  • 7
  • 48
  • 54
  • FYI the "Different way of getting Path" link (http://dailydotnettips.com/2013/10/29/different-ways-of-getting-path/) is broken. – Brian B Jun 29 '20 at 15:16
4

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

TK1
  • 396
  • 2
  • 7
  • 20