4

What are the differences between these 3 methods

  1. Directory.GetCurrentDirectory()
  2. Environment.CurrentDirectory
  3. hostingEnvironment.ContentRootPath

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 path1 = Path.Combine(Directory.GetCurrentDirectory(),
                                              "wwwroot", "img", "Image1.png");
     string path2 = Path.Combine(Environment.CurrentDirectory,
                                              "wwwroot", "img", "Image1.png");
     string path3 = Path.Combine(hostingEnvironment.ContentRootPath,
                                              "wwwroot", "img", "Image1.png");
  }
}
surfmuggle
  • 5,527
  • 7
  • 48
  • 77
Megrez7
  • 1,423
  • 1
  • 15
  • 35

1 Answers1

6

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
  • 28,238
  • 6
  • 56
  • 88
  • `IHostEnvironment` does not provide `WebRootPath` https://learn.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