Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if file exists in wwwroot? [closed]

How can I check if a file exists in wwwroot. System.IO.File needs an absolute path.

Is it necessary to convert the relative path to an absolute path first, or is there a simpler way?

like image 325
Ivan-Mark Debono Avatar asked Jan 24 '23 17:01

Ivan-Mark Debono


1 Answers

For ASP.NET Core 3, you can inject an instance of IWebHostEnvironment which has a WebRootPath property that points at your wwwroot folder. As an example:

public class HomeController : Controller
{
    private readonly IWebHostEnvironment _environment;

    public HomeController(IWebHostEnvironment environment)
    {
        _environment = environment;
    }

    public IActionResult Index()
    {
        var wwwroot = _environment.WebRootPath;
        var favicon = Path.Combine(wwwroot, "favicon.ico");
        var favicon2 = Path.Combine(wwwroot, "favicon2.ico");
        
        // true
        var exists = System.IO.File.Exists(favicon);
        // false
        var exists2 = System.IO.File.Exists(favicon2);
    }
}

That said, the property has a setter, so make sure not to overwrite it.

like image 135
John H Avatar answered Jan 29 '23 23:01

John H