How to Get Application Base Path in Asp.Net Core

While working on the back-end sometimes you need to dynamically retrieve the physical path within your application. It is quite easy to get the application base path in Asp.Net Core.

In this article, I will use the built-it service to get the content-root path and application base path in Asp.Net Core.

First of all, Inject the IHostingEnvironment on the constructor and use it later.

Examine the code below and I will explain it in the next paragraph.

For demo purpose, I have created the sample project and named it as aspnetcore_test. Here in the Home controller, I have use Constructor Injection which is one of the techniques of dependency injection.

The _hostingEnv object in the constructor of HomeController is used for getting the application root path and content root path.

The output for :
_hostingEnv.WebRootPath = “../aspnetcore_test/aspnetcore_test/wwwroot”
_hostingEnv.ContentRootPath = “../aspnetcore_test/aspnetcore_test”

Later you can use them on other methods for your requirement.

Information: Prior to Asp.Net Core RC2, you have to use IApplicationEnvironment instead of IHostingEnvironment.

Thanks for passing by.

Have a great day.

About dipneupane

Dip is a passionate Software Developer based in Kathmandu, Nepal. He chew code and smash keyboard for living. Apart from that, he writes about almost everything on buzzedcode.com.

View all posts by dipneupane →

Leave a Reply

Your email address will not be published. Required fields are marked *