UWP中使用_stat()函数访问图片库的权限问题咨询
UWP中无法用
_stat()访问图片库绝对路径的问题解决 核心结论
不能直接使用_stat()通过绝对路径访问图片库这类UWP受限目录。
原因分析
UWP运行在沙箱环境中,传统C/C++标准库的文件操作函数(如_stat())不支持UWP的权限模型:
- 即使你在清单中声明了
picturesLibrary权限,这类函数也无法识别沙箱外的路径权限,会被沙箱拦截,返回-1错误。 - 而
StorageFolder::GetFolderFromPathAsync这类WinRT API是专为UWP设计的,会自动处理沙箱权限验证,因此能正常访问授权目录。
解决方案
方法1:通过WinRT API获取文件句柄后使用_fstat()
先借助WinRT的Storage API拿到文件的Win32句柄,再用支持文件句柄的_fstat()获取状态信息:
#include <winrt/Windows.Storage.h> #include <windows.h> #include <sys/stat.h> #include <shobjidl_core.h> #include <cstdio> using namespace winrt; using namespace Windows::Storage; void GetImageFileStats() { // 目标图片路径 hstring filePath = L"C:\\Users\\<<my-user>>\\Pictures\\image_sample.png"; // 先通过WinRT API获取文件对象 StorageFile file = StorageFile::GetFileFromPathAsync(filePath).get(); // 获取IStorageItemHandleAccess接口以拿到Win32句柄 com_ptr<IStorageItemHandleAccess> handleAccess = file.as<IStorageItemHandleAccess>(); HANDLE hFile = nullptr; winrt::check_hresult(handleAccess->Create( GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &hFile)); // 将句柄转为文件流指针,传入_fstat FILE* filePtr = _fdopen((intptr_t)hFile, "rb"); struct _stat fileStat; if (_fstat(_fileno(filePtr), &fileStat) == 0) { // 成功获取文件状态,可读取fileStat中的信息(如大小、修改时间等) } // 清理资源 fclose(filePtr); // 关闭文件流会自动关闭句柄 }
方法2:直接使用UWP原生API获取文件属性
如果只是需要文件的大小、创建时间等基础信息,完全可以用UWP的BasicProperties类,无需依赖C运行时函数:
#include <winrt/Windows.Storage.h> using namespace winrt; using namespace Windows::Storage; void GetImageFileProperties() { hstring filePath = L"C:\\Users\\<<my-user>>\\Pictures\\image_sample.png"; StorageFile file = StorageFile::GetFileFromPathAsync(filePath).get(); BasicProperties props = file.GetBasicPropertiesAsync().get(); uint64_t fileSize = props.Size(); // 文件大小(字节) DateTime creationTime = props.DateCreated(); // 文件创建时间 }
内容的提问来源于stack exchange,提问作者Patryk Kowalski
相关产品推荐
相关产品推荐

