1

我是 Windows Store App 开发的新手,我有一个用 C# 编写的应用程序,它试图获取指定目录及其子目录中所有文件的大小。StorageFolder.GetFilesAsync() 方法适用于具有少量文件的目录,但是对于包含大量文件的目录,它会在只有 2GB RAM 的设备(例如许多 RT 平板电脑)上产生 OOM 异常。有没有办法解决这个问题,允许应用程序以较小的块处理文件,而不是构建所有文件的列表(这似乎非常低效),如下面的代码所示,任何帮助将不胜感激......

StorageFolderQueryResult queryResult = KnownFolders.RemovableDevices.CreateFolderQueryWithOptions(new QueryOptions(CommonFolderQuery.DefaultQuery));

folderList = await queryResult.GetFoldersAsync();
foreach (StorageFolder folder in folderList)
{
    IReadOnlyList<StorageFile> fileList = await folder.GetFilesAsync(CommonFileQuery.DefaultQuery);

    foreach (StorageFile file in fileList)
    {
        BasicProperties properties = await file.GetBasicPropertiesAsync();
        size += properties.Size;
    }
}
4

1 回答 1

2

使用StorageFolderQueryResult.GetFoldersAsync(uint, uint)withStorageFolderQueryResult.GetItemCountAsync可以分块查询文件夹。

就像是:

StorageFolderQueryResult queryResult = KnownFolders.RemovableDevices.CreateFolderQueryWithOptions(new QueryOptions(CommonFolderQuery.DefaultQuery));

uint numItems = await queryResult.GetItemCountAsync();
uint chunkSize = 50;

for(uint startingIndex = 0; startingIndex < numItems; startingIndex += chunkSize)
{
    var folderList = await queryResult.GetFoldersAsync(startingIndex, chunkSize);
    foreach (StorageFolder folder in folderList)
    {
        IReadOnlyList<StorageFile> fileList = await folder.GetFilesAsync(CommonFileQuery.DefaultQuery);

        foreach (StorageFile file in fileList)
        {
            BasicProperties properties = await file.GetBasicPropertiesAsync();
            size += properties.Size;
        }
    }
}   

chunkSize您可以根据您希望如何绑定内存来增加或减少。

希望这可以帮助。快乐编码!

于 2013-06-06T19:56:46.663 回答