59

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?

4 Answers 4

100
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("~")
Sign up to request clarification or add additional context in comments.

2 Comments

This caused a NullReferenceException as described here. I think HttpRuntime.AppDomainAppPath is preferable as per here and here (read comments and go to the link).
I get "Server operation is not available in this context" when I try this.
46

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

3 Comments

This is very useful when you cannot use HttpContext to get the Server object
This method returned what I was looking for: The root URL of my application running in IIS. Server.MapPath returns a file directory.
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);
7

Another possibility is AppDomain.CurrentDomain.BaseDirectory

Some additional ways: Different ways of getting Path

1 Comment

FYI the "Different way of getting Path" link (dailydotnettips.com/2013/10/29/different-ways-of-getting-path) is broken.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.