Free Web Development Online Tutorials, Learn to Code
How to retrieve static files images from wwwroot folder in Asp.net Core, Delete files from wwwroot .net core

Retrieve static files in Asp.net Core

Here you learn how to retrieve files from any folder under wwwroot in asp.net core.

Retrieve images from wwwroot

In earlier article i shared how to upload multiple image files in asp.net core wwwroot folder

Now we learn how to retrieve image files from any folder under wwwroot, display images on screen and delete image in asp.net core web application.

Retrieve and delete static files images in Asp.net Core

Load Images in Controller Asp.net Core

First we design a model with few properties, so in controller we can fill those properties and access in razor view, in model we have a FileInfo array type property called “Files”, we will use this property for retrieving images from a folder under wwwroot in Asp.net core

Here is how the model code will look like.

namespace WebTrainingRoom.Models
{
    public class FileManagerModel
    {        
        public FileInfo[] Files { get; set; }       
        public IFormFile IFormFile { get; set; }
        public List<IFormFile> IFormFiles { get; set; }        
    }
}

We need to access the root folder of the application in our controller code, and to do that we need use PhysicalFileProvider service.

Add Middleware Service in Startup

You need to add following Middleware Service reference in ConfigureServices method of Startup.cs file. In your ConfigureService method there may be many other services already added, so just add IFileProvider Service also.

using Microsoft.Extensions.FileProviders;
using System.IO;
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IFileProvider>(new PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")));
    services.AddMvc();
}

Get file path in asp.net Core

To get folder reference in Asp.net Core Controller you need to Add IHostingEnvironment in Controller with DI (Dependency Injection)

Now you need the folder reference where you want to save all uploaded image files, and to get that you need an instance of IHostingEnvironment, so in controller constructor we create the instance using dependency injection

private readonly IHostingEnvironment _hostingEnvironment;
public fileuploadController(IHostingEnvironment hostingEnvironment)
{
    _hostingEnvironment = hostingEnvironment;
}
Now whenever you want to access wwwroot folder in your controller, just write _hostingEnvironment.WebRootPath

Now in controller code we fetch all images from specified folder (“userimages” under “wwwroot”) , and set in model property (File Array)

using Microsoft.AspNetCore.Mvc;
using System.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
using WebTrainingRoom.Models;
public IActionResult index()
{
    FileManagerModel model = new FileManagerModel();
    var userImagesPath = Path.Combine(_hostingEnvironment.WebRootPath, "userimages");
    DirectoryInfo dir = new DirectoryInfo(userImagesPath);
    FileInfo[] files = dir.GetFiles();
    model.Files = files;
    return View(model);
}

Display images from wwwroot folder

Finally, we need to display all images in our asp.net core razor view; we also have a provision to delete any image from this screen also from file system (folder under "wwwroot")

@if (Model.Files != null)
{
    foreach (FileInfo f in Model.Files)
    {
        <div class="col-lg-3">
            <img src="~/userimages/@f.Name" style="width:90%;">  
            <div style="padding:10px;text-align:center"><a href="@Url.Action("deletefile","fileupload",new { fname=f.Name})">Delete</a></div>
        </div>
    }
}
<div class="clearfix"></div>

Please take a look at the screen below.

Retrieve and delete static files images in Asp.net Core

Delete Image from folder in Asp.net core

Now as you see there is delete link under each screen in above image, once you click the image will be deleted from folder permanently and the screen will be reloaded without that image.

In razor view you need to just pass the unique identifier for that image to call an action, here I am passing the image name.

<a href="@Url.Action("deletefile","fileupload",new { fname=f.Name})">Delete</a>

Now in controller we have to write action method to receive the delete request and finally delete that image from folder and redirecting to a different action method.

public IActionResult deletefile(string fname)
{
    string _imageToBeDeleted = Path.Combine(_hostingEnvironment.WebRootPath, "userimages\\",fname);
    if ((System.IO.File.Exists(_imageToBeDeleted)))
    {
        System.IO.File.Delete(_imageToBeDeleted);
    }
    return RedirectToAction("index",new { deleted= fname });
}

Hope you understood retrieving, displaying and deleting files from asp.net core folder

 
File Upload in Asp.Net Core
ASP.NET MVC Interview Questions Answers

online courses
Asp.Net Core C# Examples | Join Asp.Net MVC Course