2

What are the differences between these 3 methods used to get the path to the image stored under wwwroot? Seems like all work the same in my case, but would like to understand if there are any other case specific differences between them or benefits of using one over another.

I use this path to subsequently load the image into Bitmap MyBitmap variable for further processing. Would like it to be environment resilient whatever it is finally deployed to Windows, Linux or container; locally or in the cloud.

Using Razor Pages with ASP.NET Core 3.0.

public class QRCodeModel : PageModel
{
    private readonly IHostEnvironment hostingEnvironment;

    public QRCodeModel(IHostEnvironment environment)
    {
        this.hostingEnvironment = environment;
    }

    public void OnGet()
    {
        string TempPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "img", "Image1.png");
        string TempPath1 = Path.Combine(Environment.CurrentDirectory, "wwwroot", "img", "Image1.png");
        string TempPath2 = Path.Combine(hostingEnvironment.ContentRootPath, "wwwroot", "img", "Image1.png");
    }
}
Megrez7
  • 1,271
  • 1
  • 10
  • 28

1 Answers1

4

There is another option:

string TempPath4 = Path.Combine(hostingEnvironment.WebRootPath, "img", "Image1.png");

WebRootPath returns the path to the wwwroot folder.

This is recommended over using the first two options as they may not return the location that you want: Best way to get application folder path

Mike Brind
  • 25,035
  • 6
  • 49
  • 82
  • `IHostEnvironment` does not provide `WebRootPath` https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.ihostenvironment?view=dotnet-plat-ext-3.0 – Megrez7 Oct 25 '19 at 16:02
  • 2
    In order to use `WebRootPath` `IWebHostEnvironment` must be used instead of `IHostEnvironment`. – Megrez7 Oct 25 '19 at 16:11