.NET 6 (.NET Core 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 the last Part and register its 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; //difference 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
.
IHostingEnvironment.WebRootPath
and then usePath.Combine
with second argument assigned to target directory. See Server.MapPath Equivalent in ASP.NET Core for further reference. – Mcbryde