Im using ImageSharp with .Net Core to process some images. To load the images and fonts I do as follows:
_image = Image.Load(@"Resources/imgs/quote_background.png");
_fonts = new FontCollection();
_font = _fonts.Install(@"Resources/fonts/Cousine-Italic.ttf");
// Image processing...
My files tree looks like:
- Solution
- - MyApp
- - - Controllers
- - - Models
- - - - Code.cs // This is where the above code is
- - - wwwroot
- - - Resources
- - - - imgs
- - - - fonts
When I am launching the application through visual studio it works fine, it finds the image. But when I deploy to AWS or to my local IIS I get the following error:
DirectoryNotFoundException: Could not find a part of the path 'C:\inetpub\wwwroot\MyApp\Resources\imgs\quote_background.png'.
What is the right way to reference this image?
Thanks
You need to use the ContentRootPath from the IHostingEnvironment, which requires you to inject an IHostingEnvironment into your controller, e.g.:
public class ImageController : Controller
{
private readonly IHostingEnvironment _hostingEnvironment;
public ImageController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public ActionResult Index()
{
var image = Image.Load(String.Format(@"{0}/Resources/imgs/quote_background.png",
_hostingEnvironment.ContentRootPath);
//etc...
}
}
There is also WebRootPath which gets you to the wwwroot.