Getting the number of files in the StorageFolder

I was working with Windows Phone 8.1 (RT) app, I wanted to know how to get the number of files inside the StorageFolder .

I know we can use StorageFolder.GetFilesAsync()

and then check the count of the returned list. But since this method takes too long and returns all items, is there a better way to do this?

+3


source to share


1 answer


You can get 3 orders of magnitude better performance if you use the Win32 API to get the number of files, but it only works in your local storage directory (it won't work for brokerage places like Pictures or Music). For example, given the following C ++ / CX component:

Heading

public ref struct FilePerfTest sealed
{
  Windows::Foundation::IAsyncOperation<uint32>^ GetFileCountWin32Async();
  uint32 GetFileCountWin32();
};

      

Implementation



uint32 FilePerfTest::GetFileCountWin32()
{
  std::wstring localFolderPath(ApplicationData::Current->LocalFolder->Path->Data());
  localFolderPath += L"\\Test\\*";
  uint32 found = 0;
  WIN32_FIND_DATA findData{0};
  HANDLE hFile = FindFirstFileEx(localFolderPath.c_str(), FindExInfoBasic, &findData, FindExSearchNameMatch, nullptr, FIND_FIRST_EX_LARGE_FETCH);

  if (hFile == INVALID_HANDLE_VALUE)
    throw ref new Platform::Exception(GetLastError(), L"Can't FindFirstFile");
  do
  {
    if ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
      ++found;
  } while (FindNextFile(hFile, &findData) != 0);

  auto hr = GetLastError();
  FindClose(hFile);
  if (hr != ERROR_NO_MORE_FILES)
    throw ref new Platform::Exception(hr, L"Error finding files");

  return found;
}

Windows::Foundation::IAsyncOperation<uint32>^ FilePerfTest::GetFileCountWin32Async()
{
  return concurrency::create_async([this]
  {
    return GetFileCountWin32();
  });
}

      

If I test this on my Lumia 920 in Release mode to get 1000 files, the Win32 version takes less than 5 milliseconds (faster if you are using the non-asynchronous version and at that speed there really doesn't need to be asynchronous), whereas using StorageFolder.GetFilesAsync().Count

takes over 6 seconds.

Edit 7/1/15

Please note that if you are targeting Windows Desktop applications you can use the method StorageFolder.CreateFileQuery

to create a bulk request and it should be faster. But unfortunately it is not supported on phone 8.1

+5


source







All Articles