2

I am trying to display all the images in a images folder I have stored in the root file. I know they have vaulted the Server.MapPath method in asp.net core. I am not sure how I would do the same functionality in .net core of creating a view model and being able to loop through all the images stored in my root images folder. Any suggestions would be great. Below is the example code I was going off of but it obviously doesn't work for.Net core.

// model
class MyViewModel
{
    public IEnumerable<string> Images { get; set; }
}

// controller
public ActionResult MyAction()
{
    var model = new MyViewModel()
{
    Images = Directory.EnumerateFiles(Server.MapPath("~/images_upload"))
                      .Select(fn => "~/images_upload/" + 
   Path.GetFileName(fn))
};
return View(model);
}
// view
@foreach(var image in Model.Images)
  {
     <img src="@Url.Content(image)" alt="Hejsan" />
  }

1 Answer 1

4

You need to use IHostingEnvironment, which you should get injected into your Controller if you specify it in the constructor.

You can then use the properties (depending on where you put your images_upload folder):

  • ContentRootPath - application's base path. This is the location of the web.config, project.json
  • WebRootPath - the physical file path to the directory that houses files intended to be browsable. By default, this is the wwwroot folder

Then use System.IO.Path.Combine()

e.g.

public class HomeController : Controller
{
    private IHostingEnvironment _env;
    public HomeController(IHostingEnvironment env)
    {
        _env = env;
    }

    public ActionResult MyAction()
    {
        var folderPath = System.IO.Path.Combine(_env.ContentRootPath, "/images_upload");
        var model = new MyViewModel()
        {
            Images = Directory.EnumerateFiles(folderPath)
                .Select(filename => folderPath + filename)
        };
        return View(model);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.