0

I want to show all images (which is in "~/files/ " folder) in asp.net mvc 5. It was like that:

public ActionResult uploadPartial()
{
     var appData = Server.MapPath("~/files");
     var images = Directory.GetFiles(appData).Select(x => new imagesviewmodel
     {
        Url = Url.Content("/files/" + Path.GetFileName(x))
     });
     return View(images);
} 

and in view

@model IEnumerable<ckeditortest.Models.imagesviewmodel>

@foreach (var image in Model)
{
    <a href="#" class="returnImage" data-url="@Request.Url.GetLeftPart(UriPartial.Authority)@image.Url">
        <img src="@image.Url" alt="Hejsan" id="#image" data-source="@image.Url" width="200" height="200"/>
    </a>
}

But in asp.net core i don't know how can i do that

teo van kot
  • 12,350
  • 10
  • 38
  • 70
Fatikhan Gasimov
  • 903
  • 2
  • 16
  • 40

1 Answers1

1

You want Directory.EnumerateFiles. See this answer for an example. You'll also have to replace Server.MapPath, as it's not available in .NET Core. You can use this code to do that (inject IHostingEnvironment and get WebRootPath from it).

Using both of the above, you get this code (untested):

public class MyController : Controller
{
    private IHostingEnvironment _env;

    public HomeController(IHostingEnvironment env)
    {
        _env = env;
    }

    public IActionResult Index()
    {
        var webRoot = _env.WebRootPath;
        var appData = System.IO.Path.Combine(webRoot, "files");

        var models = Directory.EnumerateFiles(appData).Select(x => new imagesviewmodel
        {
            Url = Url.Content(x)
        });

        return View(models);
    }
}

You can replace GetLeftPart with this (from this answer):

Request.Url.GetComponents(UriComponents.Scheme | UriComponents.StrongAuthority, UriFormat.Unescaped)
vaindil
  • 7,536
  • 21
  • 68
  • 127
  • Thanks your answer ! I will test it as soon as possible. Another quesstion how can I change this code @Request.Url.GetLeftPart(UriPartial.Authority)@image.Url ---- in view ? for asp.net core – Fatikhan Gasimov May 25 '17 at 12:47
  • @FatikhanGasimov I've updated the answer with that info. – vaindil May 25 '17 at 13:54
  • Request.Url.GetComponents(UriComponents.Scheme | UriComponents.StrongAuthority, UriFormat.Unescaped) is not worked – Fatikhan Gasimov May 25 '17 at 17:05