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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With