我正在使用 Windows Phone 8.1(RT) 应用程序,我想知道如何获取StorageFolder 中的文件数。
我知道我们可以使用 StorageFolder.GetFilesAsync()
然后检查返回的这个列表的计数。
但是由于此方法花费的时间太长并且会返回所有项目,是否有更有效的方法来完成此操作?
最佳答案
如果您使用 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 秒。
编辑 7/1/15
请注意,如果您的目标是 Windows 桌面应用程序,则可以使用 StorageFolder.CreateFileQuery
方法来创建批量查询,这应该会更快。但不幸的是,Phone 8.1 不支持它
关于c# - 获取 StorageFolder 中的文件数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29908345/