2017-09-30 46 views
0

如果一个文件夹包含很多文件(> 300..1000),并且磁盘驱动器速度不是很快,那么我无法让代码可靠地加载完整的文件列表。首先它加载几个文件(如10或100,取决于月亮的位置)。接下来的尝试(runnin相同的代码)会稍微返回更多,例如200,但不能保证这个数字会增长。UWP - 如何从文件夹中可靠地获取文件?

我试过很多变种,包括:

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; 
    } 

此代码看起来有点复杂,但我已经尝试了简单的变型:(

会很高兴得到你的帮助。

回答

0

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

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

相关问题