Surely there is a simple way of getting all files within a folder and all sub-folders in UWP? I can't seem to find any examples of it anywhere. Below is my implementation which loops through loops for a finite amount of subfolders but it is a bit ridiculous and prone to error.
var libraryFolder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync("UserLibrary");
var subFoldersLayer1 = await libraryFolder.GetFoldersAsync();
var rootFiles = await libraryFolder.GetFilesAsync();
List<StorageFile> allFiles = new List<StorageFile>();
IEnumerable<StorageFile> allFilesForScanning = new List<StorageFile>();
foreach (var _file in rootFiles)
{
itemsFoundCounter++;
if (itemsFound != null)
{
itemsFound.Report(itemsFoundCounter);
}
allFiles.Add(_file);
}
foreach (var subFolderLayer1 in subFoldersLayer1)
{
var subFoldersLayer2 = await subFolderLayer1.GetFoldersAsync();
IReadOnlyList<StorageFile> files = await subFolderLayer1.GetFilesAsync();
foreach (var file in files)
{
itemsFoundCounter++;
if (itemsFound != null)
{
itemsFound.Report(itemsFoundCounter);
}
allFiles.Add(file);
}
foreach (var subFolderLayer2 in subFoldersLayer2)
{
var subFoldersLayer3 = await subFolderLayer2.GetFoldersAsync();
files = await subFolderLayer2.GetFilesAsync();
foreach (var file in files)
{
itemsFoundCounter++;
if (itemsFound != null)
{
itemsFound.Report(itemsFoundCounter);
}
allFiles.Add(file);
}
// Goes on like this for a bit...
I figured it out
private async Task GetAllFiles(StorageFolder folder, List<StorageFile> allFiles, IProgress<int> itemsFound)
{
foreach (StorageFile file in await folder.GetFilesAsync())
{
if (file.FileType == ".ext")
{
allFiles.Add(file);
if (itemsFound != null)
{
itemsFound.Report(itemsFoundCounter);
}
}
}
foreach (StorageFolder subfolder in await folder.GetFoldersAsync())
{
await GetAllFiles(subfolder, allFiles, itemsFound);
}
}