简体   繁体   中英

How can I get files from multiple folders in ASP.NET MVC?

public ActionResult DisplayFiles()
{
    var getCategory = dbcontext.tblDetails.Select(x => x.Category).Distinct().ToList();
    ViewBag.Category = getCategory;

    foreach (string category in getCategory)
    {
        ViewBag.Images = Directory.EnumerateFiles(Server.MapPath("~/" + category)).Select(fn => "~/" + category + "/" + Path.GetFileName(fn));
    }

    return View();
}

I tried to upload it like this where category returns the folder names from the database of table tblDetails from where I want to get the files.

Actually the above code overrides the folder name after every iteration of the loop and provides the last category name to the Viewbag.Images and only display the files of that folder

Change your loop to something like: EDIT

List<string> images = new List<string>;
foreach (string category in getCategory)
{
    images.AddRange(Directory.EnumerateFiles(Server.MapPath("~/" + category))
               .Select(fn => "~/" + category + "/" + Path.GetFileName(fn)).ToList());
}
ViewBag.Images = images;

What you are doing in your loop is returning only the final image as the result will be over written on each iteration.

Actually the above code overrides the folder name after every iteration of the loop and provides the last category name to the Viewbag.Images and only display the files of that folder

You could try to use List<IEnumerable<string>> to store all folders with their file names

var data = new List<IEnumerable<string>>();

foreach (string category in getCategory)
{
    var images = Directory.EnumerateFiles(Server.MapPath("~/" + category)).Select(fn => "~/" + category + "/" + Path.GetFileName(fn));
    data.Add(images);
}
ViewBag.Images = data;

Then in your view, you could display them as a group like

@foreach( var folder in ViewBag.Images)
{      
    <ul>
        @foreach (var image in folder)
        {
            <li>@image</li>
        }
    </ul>

 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM