微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从 Windows::Storage::StorageFile 创建 std::filesystem::exists() 兼容路径?

如何解决如何从 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() 的路径无效。

任何指出我哪里出错的帮助将不胜感激!

这个问题最初被标记this question 的重复,但是该解决方案似乎不起作用,因为它需要 CLI(?) 而我认为我正在使用 WinRT(但是我除了在包含中提供 winrt 之外,无法在我的项目或设置中找到要检查的位置)。

解决方法

在 Windows 运行时(使用 C++/CX 或 C++/WinRT)中要记住的 StorageFile 的关键是 (a) 它不一定是磁盘上的文件,并且 (b) 即使它是一个磁盘上的文件,您不需要直接打开它的权限。

可用于在 UWP FilePicker 提供的 StorageFile 实例上执行传统文件 I/O 操作的唯一“一般安全”模式是从中创建临时目录副本,然后解析临时目录复制:

C++/CX

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

C++/WinRT

#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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。