What is the equivalent of Server.MapPath in ASP.NET Core?

.Net 6 (.NetCore 3 and above)

For example I want to locate ~/wwwroot/CSS

public class YourController : Controller
{
    private readonly IWebHostEnvironment _webHostEnvironment;

    public YourController (IWebHostEnvironment webHostEnvironment)
    {
        _webHostEnvironment= webHostEnvironment;
    }

    public IActionResult Index()
    {
        string webRootPath = _webHostEnvironment.WebRootPath;
        string contentRootPath = _webHostEnvironment.ContentRootPath;

        string path ="";
        path = Path.Combine(webRootPath , "CSS");
        //or path = Path.Combine(contentRootPath , "wwwroot" ,"CSS" );
        return View();
    }
}

Some Tricks

Also if you don’t have a controller or service,follow last Part and register it’s class as a singleton.
Then, in Startup.ConfigureServices:

services.AddSingleton<your_class_Name>();

Finally, inject your_class_Name where you need it.


.Net Core 2

For example I want to locate ~/wwwroot/CSS

public class YourController : Controller
{
    private readonly IHostingEnvironment _HostEnvironment; //diference is here : IHostingEnvironment  vs I*Web*HostEnvironment 

    public YourController (IHostingEnvironment HostEnvironment)
    {
        _HostEnvironment= HostEnvironment;
    }

    public ActionResult Index()
    {
        string webRootPath = _HostEnvironment.WebRootPath;
        string contentRootPath = _HostEnvironment.ContentRootPath;

        string path ="";
        path = Path.Combine(webRootPath , "CSS");
        //or path = Path.Combine(contentRootPath , "wwwroot" ,"CSS" );
        return View();
    }
}

MoreDetails

Thanks to @Ashin but IHostingEnvironment is obsoleted in MVC core 3!!

according to this :

Obsolete types (warning):

Microsoft.Extensions.Hosting.IHostingEnvironment
Microsoft.AspNetCore.Hosting.IHostingEnvironment
Microsoft.Extensions.Hosting.IApplicationLifetime
Microsoft.AspNetCore.Hosting.IApplicationLifetime
Microsoft.Extensions.Hosting.EnvironmentName
Microsoft.AspNetCore.Hosting.EnvironmentName

New types:

Microsoft.Extensions.Hosting.IHostEnvironment
Microsoft.AspNetCore.Hosting.IWebHostEnvironment : IHostEnvironment
Microsoft.Extensions.Hosting.IHostApplicationLifetime
Microsoft.Extensions.Hosting.Environments 

So you must use IWebHostEnvironment instead of IHostingEnvironment.

Leave a Comment