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

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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

Method 3

Another possibility is
AppDomain.CurrentDomain.BaseDirectory

Some additional ways:
Different ways of getting Path

Method 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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x