Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

asp.net

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?

like image 997
David Thielen Avatar asked Jul 16 '13 17:07

David Thielen


People also ask

Is located in the root directory of an ASP NET application?

By default, the wwwroot folder in the ASP.NET Core project is treated as a web root folder. Static files can be stored in any folder under the web root and accessed with a relative path to that root.

Where is the root directory of an application?

The Web application root is the folder on your hard disk that corresponds to this URL namespace. For example, placing a file called file. htm in the Web application root folder results in an available URL at http://example/file.htm.

Where is the server root directory?

Instructions. For the Grid, a website's root directory is the …/html folder. This is located in the file path /domains/example.com/html. The root directory can be viewed/accessed through File Manager, FTP, or SSH.

How do I get the root path in .NET Core?

The Application Base (Root) path is available in the ContentRootPath property of the interfaces IHostingEnvironment (. Net Core 2.0) and IWebHostEnvironment (. Net Core 3.0) in ASP.Net Core. The IHostingEnvironment is an interface for .


2 Answers

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("~") 
like image 62
debracey Avatar answered Sep 30 '22 22:09

debracey


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); 
like image 25
Christian Hayter Avatar answered Sep 30 '22 21:09

Christian Hayter