I am trying to convert a layout page to .net core 2.0. unfortunately in razor Server.MapPath is no longer available.
I am trying to find the equivalent in a .cshtml page for
<div style="height: 0px; width: 0px; position: absolute; visibility: hidden;">
@Html.Raw(System.IO.File.ReadAllText(Server.MapPath("~/Content/images/svg-defs.svg")))
</div>
In ASP.NET Core, you can use the IHostingEnvironment service to gain access to certain paths of the webapp.
There are two interesting properties on this object:
ContentRootPath: the path to the applications base path (where you would usually find appsettings.json, Program.cs, etcWebRootPath: the path to the /wwwroot directory, which is what you are looking for.To get access to the IHostingEnvironment service, simply inject it in the constructor of your controller and hold on it with a field.
public class HomeController : Controller
{
private IHostingEnvironment _env;
public HomeController(IHostingEnvironment env)
{
_env = env;
}
}
Now, in an action method of this Controller, you can now construct the physical path to a file using System.IO.Path.Combine and the WebRootPath property.
public IActionResult Index()
{
ViewBag.FilePath = Path.Combine(_env.WebRootPath, @"Content\images\svg-defs.svg");
return View();
}
In this example I added the resulting path to the ViewBag to easily display it in the Index view:
<h2>Index View</h2>
<p>Filepath: @ViewBag.FilePath</p>
This would print something along the lines of C:\MySite\wwwroot\Content\images\svg-defs.svg
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