获取 StorageFolder 中的文件数

Getting number of files in StorageFolder

我正在使用 Windows Phone 8.1(RT) 应用程序,我想知道如何获取 StorageFolder 中的文件数.

我知道我们可以使用 StorageFolder.GetFilesAsync() 然后检查返回的这个列表的计数。 但是由于此方法花费的时间太长,而且 returns 所有项目是否有更有效的方法来完成此操作?

如果您使用 Win32 API 获取文件计数,您可以获得 3 个数量级的性能提升,但它仅适用于您的本地存储目录(它不适用于图片或音乐等代理位置)。例如,给定以下 C++/CX 组件:

页眉

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

实施

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

如果我在我的 Lumia 920 上以 Release 模式测试它以获取 1,000 个文件,Win32 版本需要不到 5 毫秒 (如果你使用非异步版本会更快,并且在那个速度下真的不需要异步)而使用 StorageFolder.GetFilesAsync().Count 需要超过 6

编辑 2015 年 7 月 1 日

请注意,如果您的目标是 Windows 桌面应用程序,则可以使用 StorageFolder.CreateFileQuery 方法创建批量查询,这应该会更快。但不幸的是,Phone 8.1

不支持它