Search code examples
uwpc++-winrt

Fast way to retrieve file sizes in a folder in UWP


I want to sum all file sizes in my application's TempState folder using below code which works fine.

const auto tempFolder { ApplicationData::Current().TemporaryFolder() };
int64_t size { 0 };

const QueryOptions options { CommonFolderQuery::DefaultQuery };
options.FolderDepth(FolderDepth::Shallow);
options.IndexerOption(IndexerOption::UseIndexerWhenAvailable);
options.SetPropertyPrefetch(PropertyPrefetchOptions::BasicProperties, {});

try
{
    for (auto item : co_await tempFolder.CreateFileQueryWithOptions(options).GetFilesAsync())
    {
        size += (co_await item.GetBasicPropertiesAsync()).Size();
    }

    // do something with the size
}
catch (winrt::hresult_error& err)
{
    // ...
}

I currently have just short of 3000 items in the TempState folder and above code takes 20 seconds to compute the sum of file sizes. There needs to be a way to speed this up, right?


What I've tried so far is using

options.IndexerOption(IndexerOption::OnlyUseIndexerAndOptimizeForIndexedProperties);

but then GetFilesAsync returns no files at all.


What can be done to (drastically) improve performance here?


Solution

  • I would prefer a more C++/WinRT way, but my current workaround is to simply #include <filesystem> and to then use

    const auto tempFolder { ApplicationData::Current().TemporaryFolder() };
    int64_t size { 0 };
    
    for (const auto& file : std::filesystem::directory_iterator(winrt::to_string(tempFolder.Path())))
    {
        size += std::filesystem::file_size(file.path().string());
    }
    

    which runs in an instant.