Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the virtual path of File from wwwroot folder of asp.net core app?

I want to get the virtual path to my index.html file which is present in wwwroot folder of my asp.net core web API. I have attached my picture of code which will explain the situation of this problem.

this is the image of my code please look at this

right now I am just using its full path which is not convenient method of using path like this so that is why I want to get virtual path of this file so that on any other server I will not face any problems.


2 Answers

Updated

Inject IWebHostEnvironment in your controller and use its WebRootPath to access your files

using Microsoft.AspNetCore.Hosting;
//...

public class AccountController : Controller
{
    private readonly IWebHostEnvironment _hostingEnvironment;

    public AccountController(IWebHostEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }

    //...

    string htmlFilePath = Path.Combine(_hostingEnvironment.WebRootPath, "EmailTemplate", "index.html");

    //...
}

Answer for older ASP.NET Core versions

Inject IHostingEnvironment in your controller and use its WebRootPath to access your files

using Microsoft.AspNetCore.Hosting;
//...

public class AccountController : Controller
{
    private readonly IHostingEnvironment _hostingEnvironment;

    public AccountController(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }

    //...
}
like image 68
Alexander Avatar answered Oct 26 '25 01:10

Alexander


In 2023 instead of IHostingEnvironment you will use IWebHostEnvironment and inject that like Alexander response.

like image 45
PurTahan Avatar answered Oct 26 '25 00:10

PurTahan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!