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?
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.
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.
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.
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 .
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("~")
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With