Getting number of files in StorageFolder

2019-05-18 07:12发布

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

I know we can use StorageFolder.GetFilesAsync() and then check the count of this list returned. But since this method takes too long and returns all items is there more efficient method of getting this done?

1条回答
劫难
2楼-- · 2019-05-18 07:37

You can get 3 orders of magnitude faster performance if you use Win32 APIs to get the file count, but it only works for your local storage directory (it won't work for brokered locations such as Pictures or Music). For example, given the following C++/CX component:

Header

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 1,000 files, the Win32 version takes less than 5 milliseconds (faster if you use the non-async version, and at that speed there's really no need to be async) whereas using StorageFolder.GetFilesAsync().Count takes more than 6 seconds.

Edit 7/1/15

Note that if you are targeting Windows Desktop apps, you can use the StorageFolder.CreateFileQuery method to create a bulk query, and that should be faster. But unfortunately it isn't supported on Phone 8.1

查看更多
登录 后发表回答