22

In my MVC application I have the following paths;

  • /content/images/full
  • /content/images/thumbs

How would I, in my c# controller, get a list of all the files within my thumbs folder?

Edit

Is Server.MapPath still the best way?

I have this now DirectoryInfo di = new DirectoryInfo(Server.MapPath("/content/images/thumbs") ); but feel it's not the right way.

is there a best practice in MVC for this or is the above still correct?

griegs
  • 22,624
  • 33
  • 128
  • 205

2 Answers2

52

.NET 4.0 has got a more efficient method for this:

Directory.EnumerateFiles(Server.MapPath("~/Content/images/thumbs"));

You get an IEnumerable<string> on which you can iterate on the view:

@model IEnumerable<string>
<ul>
    @foreach (var fullPath in Model)
    {
        var fileName = Path.GetFileName(fullPath);
        <li>@fileName</li>
    }
</ul>
slfan
  • 8,950
  • 115
  • 65
  • 78
  • 5
    If you have problem with finding _Server_, check out this question : [Cannot use Server.MapPath](http://stackoverflow.com/questions/11105768/cannot-use-server-mappath) – Alex Oct 19 '13 at 06:12
  • Can you serve these files by providing a link to the full path, or do you need a handler for that? – JsonStatham Oct 25 '15 at 17:49
  • @selectDistinct Not sure what you mean. Server.MapPath converts the virtual path into a physical directory path. Of course the process that executes the code needs the right to access this path. The OP asked for a list of files – slfan Nov 05 '15 at 19:43
10
Directory.GetFiles("/content/images/thumbs")

That will get all the files in a directory into a string array.

Daniel T.
  • 37,212
  • 36
  • 139
  • 206
  • 2
    @Daniel i can't get this to work. it maps at c:\content\images\thumbs rather than at my web application level. – griegs Jan 11 '10 at 04:45
  • Can you provide more info on what you're trying to do? It sounds like you're trying to return a list of file paths to the view. In that case, in the view, try using `<%= Server.MapPath(filePath) %>`, where filePath is a local path. – Daniel T. Jan 11 '10 at 04:59
  • Whoops, just noticed that `Server.MapPath()` actually converts a server path to a file path. Looking for some other solutions now... – Daniel T. Jan 11 '10 at 05:03
  • I found this: http://stackoverflow.com/questions/3164/asp-net-absolute-path-back-to-web-relative-path Seems a bit brittle though. I'd probably just get the filename using `Path.GetFileName(file)` and append the virtual path in front of it. – Daniel T. Jan 11 '10 at 05:12