Abs*_*ith 3 c# windows-runtime windows-phone-8.1
我正在使用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();
};
Run Code Online (Sandbox Code Playgroud)
履行
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();
});
}
Run Code Online (Sandbox Code Playgroud)
如果我在发布模式下在我的Lumia 920上测试这个以获得1,000个文件,那么Win32版本需要不到5 毫秒(如果你使用非异步版本更快,并且在那个速度下真的没有必要是异步的)而使用StorageFolder.GetFilesAsync().Count需要超过6 秒.
编辑7/1/15
请注意,如果您要定位Windows桌面应用,则可以使用该StorageFolder.CreateFileQuery方法创建批量查询,这应该更快.但不幸的是,手机8.1不支持它