In this article I will explain a short tutorial with example on how to use IWebHostEnvironment interface in ASP.Net Core.
Microsoft has permanently removed Server.MapPath function from .Net Core and introduced a new interfaces IWebHostEnvironment for .Net Core 3.0.
 
 
What is IWebHostEnvironment
The IWebHostEnvironment is an interface for .Net Core 3.0.
The IWebHostEnvironment interface need to be injected as dependency in the Controller and then later used throughout the Controller.
The IWebHostEnvironment interface have two properties.
1. WebRootPath – Path of the www folder.
2. ContentRootPath – Path of the root folder which contains all the Application files.
 
 
Namespaces
You will need to import the following namespace.
using Microsoft.AspNetCore.Hosting;
 
 
Using IWebHostEnvironment
In the below example, the IWebHostEnvironment is injected in the Controller and assigned to the private property Environment and later used to get the WebRootPath and ContentRootPath.
public class HomeController : Controller
{
    private IWebHostEnvironment Environment;
 
    public HomeController(IWebHostEnvironment _environment)
    {
        Environment = _environment;
    }
 
    public IActionResult Index()
    {
        string wwwPath = this.Environment.WebRootPath;
        string contentPath = this.Environment.ContentRootPath;
 
        return View();
    }
}
 
 
Screenshot
Using IWebHostEnvironment in ASP.Net Core