如何从Windows::Storage::StorageFile创建std::filesystem::exists()兼



我使用FileOpenPicker在Windows通用应用程序中获取文件(StorageFile^)。这似乎工作正常,如果我输出StorageFile->Path->Data(),它返回预期的文件路径(C:…MyFile.txt)。

当我试图打开它并将内容转储到字符串时,事情会出错(字符串没有收到任何内容),因此作为第一步,我试图用std::filesystem::exists()验证文件路径。

将其剪短到相关位:

void MyClass::MyFunction(StorageFile^ InFile)
{
std::filesystem::path FilePath = InFile->Path->Data();
if (std::filesystem::exists(FilePath))
{
//Do things
}
}

当我运行这个时,我得到一个异常:

Exception thrown at 0x7780A842 in MyApp.exe: Microsoft C++ exception: std::filesystem::filesystem_error at memory location 0x039BC480.
Unhandled exception at 0x7AACF2F6 (ucrtbased.dll) in MyApp.exe: An invalid parameter was passed to a function that considers invalid parameters fatal.

看起来,我试图传递给std::filesystem::exists()的路径是无效的。

任何帮助指出我在哪里出错将非常感激!

这个问题最初被标记为这个问题的副本,但是解决方案似乎不起作用,因为它需要CLI(?),而我认为我正在使用WinRT(但是我找不到在我的项目或设置中检查的地方,超出了在包含中可用的WinRT)。

关于StorageFile在Windows运行时(使用c++/CX或c++/WinRT)要记住的关键事情是(a)它不一定是磁盘上的文件,(b)即使它是磁盘上的文件,你也不一定有直接打开它的权限。

在UWP FilePicker提供的StorageFile实例上进行传统文件I/O操作时,您可以使用的唯一"一般安全"模式是从它创建一个临时目录副本,然后解析临时副本:

c++/残雪

#include <ppltasks.h>
using namespace concurrency;
using Windows::Storage;
using Windows::Storage::Pickers;
auto openPicker = ref new FileOpenPicker();
openPicker->ViewMode = PickerViewMode::Thumbnail; 
openPicker->SuggestedStartLocation = PickerLocationId::PicturesLibrary; 
openPicker->FileTypeFilter->Append(".dds"); 
create_task(openPicker->PickSingleFileAsync()).then([](StorageFile^ file)
{
if (file)
{
auto tempFolder = Windows::Storage::ApplicationData::Current->TemporaryFolder;
create_task(file->CopyAsync(tempFolder, file->Name, NameCollisionOption::GenerateUniqueName)).then([](StorageFile^ tempFile)
{
if (tempFile)
{
std::filesystem::path FilePath = tempFile->Path->Data();
...
}
});
}
});
WinRT <<h2> C + +//h2>
#include "winrt/Windows.Storage.h"
#include "winrt/Windows.Storage.Pickers.h"
using namespace winrt::Windows::Storage;
using namespace winrt::Windows::Storage::Pickers;
FileOpenPicker openPicker;
openPicker.ViewMode(PickerViewMode::Thumbnail);
openPicker.SuggestedStartLocation(PickerLocationId::PicturesLibrary);
openPicker.FileTypeFilter().Append(L".dds");
auto file = co_await openPicker.PickSingleFileAsync();
if (file)
{
auto tempFolder = ApplicationData::Current().TemporaryFolder();
auto tempFile = co_await file.CopyAsync(tempFolder, file.Name(), NameCollisionOption::GenerateUniqueName);
if (tempFile)
{
std::filesystem::path FilePath = tempFile.Path().c_str();
...
}
}

参见Microsoft Docs

相关内容

最新更新