How to get filename within folders in WEB API server

Asked

Viewed 1,199 times

3

I have a directory Archive/Uploads

inserir a descrição da imagem aqui

And I would like to list all the files, within this directory I have N folders.

what I’ve got so far is here.

string path = HttpContext.Current.Server.MapPath("~//Arquivos//Uploads");
            string[] files = System.IO.Directory.GetFiles(path);

1 answer

3


Utilize Enumeratefiles to get the files from a given directory by configuring the third parameter System.IO.SearchOption.AllDirectories so that the search is done in all directories.

string path = HttpContext.Current.Server.MapPath("~//Arquivos//Uploads");
IEnumerable<string> files = System.IO.Directory.EnumerateFiles(path,
                                      "*.*",
                                       System.IO.SearchOption.AllDirectories);

Observing: System.IO.Directory.GetFiles can also be used in the same way having also 3 pan the same definition of System.IO.SearchOption.AllDirectories.

System.IO.Directory.Getfiles(path, "*.*", System.IO.SearchOption.AllDirectories);


Using Linq can work better this information and get only the name of the files:

var result = System.IO.Directory.EnumerateFiles(path, 
                      "*.*", 
                      System.IO.SearchOption.AllDirectories)
                .Select(c => 
                       c.Split(new string[] { "\\" }, StringSplitOptions.None).Last())
                .ToArray();

References:

  • 1

    worked beautifully. However, the answer I have is the way C:\Users\renan.carlos\Source\Repos\CodingCraft\ExerciciosCo‌​dingCraft\MusicFileS‌​erver.API\Arquivos\U‌​ploads\docx\Coding Craft ASP.NET MVC 1.docx To get just the file name, I need to give a Replace from the end to the beginning until the first bar ? Or has a better way to do? You’d rather I ask a new question ?

  • 1

    @Renancarlos did the editing!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.