肯定有一种简单的方法可以获取文件夹中的所有文件以及UWP中的所有子文件夹吗?我似乎在任何地方都找不到任何例子。下面是我的实现,它循环遍历有限数量的子文件夹的循环,但它有点荒谬且容易出错。
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...
我想通了
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);
}
}