0

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

James South
  • 8,803
  • 3
  • 53
  • 110
João Menighin
  • 2,681
  • 6
  • 27
  • 63

2 Answers2

2

You want to make sure you mark the files in your Resources folder as 'Copy to Output Directory' = 'Copy if newer'

Property screen shot showing copy to output directy set to copy if newer

that will make sure the files end up in your output when you publish the site.

tocsoft
  • 1,029
  • 12
  • 16
1

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.

Matt
  • 9,685
  • 4
  • 37
  • 36
  • Hi Matt, thanks for the answer. I did as you said and still got the same error. It seems it is mapping to the same directory as before... When I publish the project the Resource folder indeed is not generated... Do you think I have to configure something...? – João Menighin Jul 16 '17 at 14:11
  • OK, see the other answer and [this one](https://stackoverflow.com/a/42713770/934407), are your images actually being published? – Matt Jul 17 '17 at 10:05
  • Thanks Matt... It did solve although I had to manually edit my .csproj because visual studio was prompting an error when I tried to set the properties... – João Menighin Jul 18 '17 at 13:07