【问题标题】:UWP - How to reliably get files from folder?UWP - 如何可靠地从文件夹中获取文件?
【发布时间】:2017-09-30 21:56:19
【问题描述】:

如果一个文件夹包含许多文件 (>300..1000),并且磁盘驱动器不是很快,那么我无法让代码可靠地加载完整的文件列表。首先它会加载一些文件(比如 10 个或 100 个,取决于月球位置)。下一次尝试(运行相同的代码)返回稍微多一点,例如 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;
    }

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

很高兴得到您的帮助..

【问题讨论】:

    标签: uwp getfiles


    【解决方案1】:

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

    枚举大量文件的推荐方法是使用 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。请参考。

    【讨论】:

      猜你喜欢
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-07
      • 2014-01-18
      • 2016-02-17
      • 1970-01-01
      相关资源
      最近更新 更多