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?
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.
Will get you the root directory of the current application, as a path on the disk. E.g.,
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
HttpRuntime.AppDomainAppPath is useful if you don’t have a
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);
Another possibility is
Some additional ways:
Different ways of getting Path
You can get this from Server.MapPath method.
Here is the MSDN Link: