UWP - 如何可靠地从文件夹中获取文件?

UWP - How to reliably get files from folder?

如果一个文件夹包含很多文件 (>300..1000),并且磁盘驱动器不是很快,那么我无法获取代码来可靠地加载完整的文件列表。首先它会加载一些文件(比如 10 或 100,取决于月亮的位置)。下一次尝试(运行相同的代码)return 稍微多一些,例如 200,但不能保证这个数字会增长。

我尝试了很多变体,包括:

res = new List<StorageFile>(await query.GetFilesAsync());

和:

public async static Task<List<StorageFile>> GetFilesInChunks(
    this StorageFileQueryResult query)
{
        List<StorageFile> res = new List<StorageFile>();
        List<StorageFile> chunk = null;
        uint chunkSize = 200;
        bool isLastChance = false;

        try
        {
            for (uint startIndex = 0; startIndex < 1000000;)
            {
                var files = await query.GetFilesAsync(startIndex, chunkSize);
                chunk = new List<StorageFile>(files);

                res.AddRange(chunk);

                if (chunk.Count == 0)
                {
                    if (isLastChance)
                        break;
                    else
                    {
                        /// pretty awkward attempt to rebuild the query, but this doesn't help too much :)                          
                        await query.GetFilesAsync(0, 1);

                        isLastChance = true;
                    }
                }
                else
                    isLastChance = false;

                startIndex += (uint)chunk.Count;
            }
        }
        catch
        {
        }

        return res;
    }

这段代码看起来有点复杂,但我已经尝试过它更简单的变体:(

很高兴得到你的帮助..

How to reliably get files from folder?

枚举大量文件的推荐方法是使用 GetFilesAsync 上的批处理功能根据需要在文件组中分页。这样,您的应用可以在等待创建下一组文件时对文件进行后台处理。

例子

uint index = 0, stepSize = 10;
IReadOnlyList<StorageFile> files = await queryResult.GetFilesAsync(index, stepSize);
index += 10;   
while (files.Count != 0)
{
  var fileTask = queryResult.GetFilesAsync(index, stepSize).AsTask();
  foreach (StorageFile file in files)
  {
    // Do the background processing here   
  }
  files = await fileTask;
  index += 10;
}

您做的StorageFileQueryResult的扩展方法和上面类似

但是,获取文件的可靠性并不取决于上述,而是取决于QueryOptions

options.IndexerOption = IndexerOption.OnlyUseIndexer;

如果使用OnlyUseIndexer,查询会很快。但查询结果可能不完整。原因是部分文件还没有被系统索引

options.IndexerOption = IndexerOption.DoNotUseIndexer;

如果使用DoNotUseIndexer,查询会比较慢。并且查询结果完整。

这篇博客详细讲述了Accelerate File Operations with the Search Indexer。请参考。