MBS
MBS

Reputation: 707

ASP.Net core 1 list files in given directory

I need to list all files that are present in a given folder, using C# for ASP.Net core 1. Something like System.IO.Directory.GetFiles() in earlier versions.

Upvotes: 6

Views: 19231

Answers (2)

Rahmat Anjirabi
Rahmat Anjirabi

Reputation: 968

in asp.net core to list or search files you can use this way:

for example consider we want to find latest update file in this directory:

public IActionResult Get(IFileProvider fileProvider)
 {
      var files = fileProvider.GetDirectoryContents("wwwroot/updates");

      var latestFile =
                files
                .OrderByDescending(f => f.LastModified)
                .FirstOrDefault();

      return Ok(latestFile?.Name);
 }

Upvotes: 8

Joe Audette
Joe Audette

Reputation: 36736

you can do something like this:

foreach (string file in Directory.EnumerateFiles(
            pathToFolder, 
            "*" , 
            SearchOption.AllDirectories) 
            )
        {
            // do something

        }

note that I'm recursing child directories too which may or may not be what you want

Upvotes: 21

Related Questions