Get image from wwwroot/images in ASP.Net Core

Techy picture Techy · Mar 3, 2017 · Viewed 20.4k times · Source

I have an image in wwwroot/img folder and want to use it in my server side code.

How can I get the path to this image in code?

The code is like this:

Graphics graphics = Graphics.FromImage(path)

Answer

Daniel J.G. picture Daniel J.G. · Mar 4, 2017

It would be cleaner to inject an IHostingEnvironment and then either use its WebRootPath or WebRootFileProvider properties.

For example in a controller:

private readonly IHostingEnvironment env;
public HomeController(IHostingEnvironment env)
{
    this.env = env;
}

public IActionResult About(Guid foo)
{
    var path = env.WebRootFileProvider.GetFileInfo("images/foo.png")?.PhysicalPath
}

In a view you typically want to use Url.Content("images/foo.png") to get the url for that particular file. However if you need to access the physical path for some reason then you could follow the same approach:

@inject Microsoft.AspNetCore.Hosting.IHostingEnvironment env
@{ 
 var path = env.WebRootFileProvider.GetFileInfo("images/foo.png")?.PhysicalPath
}