ASP.Net core 1 list files in given directory

16,694

Solution 1

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

Solution 2

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);
 }
Share:
16,694
Bilal Sehwail
Author by

Bilal Sehwail

Software engineer with Unity experience.

Updated on June 22, 2022

Comments

  • Bilal Sehwail
    Bilal Sehwail almost 2 years

    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.

  • Bilal Sehwail
    Bilal Sehwail almost 8 years
    But "Directory.EnumerateFiles" belongs to System.IO namespace which is not found in .Net core
  • Tseng
    Tseng almost 8 years
    That's not true, see here packagesearch.azurewebsites.net/?q=EnumerateFiles. It lists you the packages where EnumerateFiles is available. This makes it easy to add it as a dependency
  • Bilal Sehwail
    Bilal Sehwail almost 8 years
    I see it and the version of all packages is the same "4.0.1-rc2-24027" which I try it before and it told me it is not supported in .Net core.
  • Joe Audette
    Joe Audette almost 8 years
    @bilal1409 suspect something wrong in your project.json, post that so we can see it
  • ctekse
    ctekse over 5 years
    This should be the correct answer, see the docs
  • Pramil Gawande
    Pramil Gawande about 4 years
    Worked like a charm in the first try. Thanks!