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);
}
Comments
-
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 almost 8 yearsBut "Directory.EnumerateFiles" belongs to System.IO namespace which is not found in .Net core
-
Tseng almost 8 yearsThat'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 almost 8 yearsI 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 almost 8 years@bilal1409 suspect something wrong in your project.json, post that so we can see it
-
ctekse over 5 yearsThis should be the correct answer, see the docs
-
Pramil Gawande about 4 yearsWorked like a charm in the first try. Thanks!