Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get files in a folder

Tags:

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?

like image 614
griegs Avatar asked Jan 11 '10 04:01

griegs


People also ask

How do I get a list of files in a folder in CMD?

You can use the DIR command by itself (just type “dir” at the Command Prompt) to list the files and folders in the current directory.

How do I get a list of files in a directory in Python?

Use the listdir() and isfile() functions of an os module to list all files of a directory.


2 Answers

.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> 
like image 189
slfan Avatar answered Oct 27 '22 09:10

slfan


Directory.GetFiles("/content/images/thumbs") 

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

like image 42
Daniel T. Avatar answered Oct 27 '22 09:10

Daniel T.