Iterate through a site relative path to find files

2019-07-07 01:36发布

问题:

I have a folder in my web application (ASP.NET MVC 3) which contains a set of images. I want to use a foreach loop to iterate through the folder to get the site relative paths which I can then append to an image tag.

Example

<div class="slides">
@foreach(string file in ?????)
{
    <img src="@file" alt="filename without extension">
}
</div>

How do I do this?

NOTE: my current foreach loop is trying to look through a physical path and returns this error

Could not find a part of the path 'C:\Content\Images\Photography\Slides\'.

回答1:

Assuming you'd like to enumerate the files in a path relative to the website's root, you could do:

@foreach (var file in 
    Directory.GetFiles(Server.MapPath("~/Content/Images/Photography/Slides")))