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.
Asked
Active
Viewed 1.8k times
6

Peter David Carter
- 2,548
- 8
- 25
- 44

MBS
- 673
- 2
- 16
- 48
2 Answers
21
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

Joe Audette
- 35,330
- 11
- 106
- 99
-
But "Directory.EnumerateFiles" belongs to System.IO namespace which is not found in .Net core – MBS May 31 '16 at 13:31
-
That's not true, see here http://packagesearch.azurewebsites.net/?q=EnumerateFiles. It lists you the packages where EnumerateFiles is available. This makes it easy to add it as a dependency – Tseng May 31 '16 at 13:38
-
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. – MBS May 31 '16 at 13:44
-
@bilal1409 suspect something wrong in your project.json, post that so we can see it – Joe Audette May 31 '16 at 13:52
-
Worked like a charm in the first try. Thanks! – Pramil Gawande Jan 31 '20 at 14:16
8
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);
}

Rahmat Anjirabi
- 868
- 13
- 16
-
2This should be the correct answer, see [the docs](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/file-providers?view=aspnetcore-1.0) – ctekse Jan 01 '19 at 21:55