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

C++ 如何从Windows::Storage::StorageFile创建std::filesystem::exists()兼容路径?,c++,c++-cx,c++-winrt,C++,C++ Cx,C++ Winrt,我正在使用FileOpenPicker在Windows通用应用程序中获取文件(StorageFile^)。这似乎工作正常,如果我输出StorageFile->Path->Data(),它将返回预期的文件路径(C:…\MyFile.txt) 当我试图打开它并将内容转储到字符串时,出现了错误(字符串没有收到任何内容),因此第一步,我尝试使用std::filesystem::exists()验证文件路径 要将其剪切到相关位,请执行以下操作: void MyClass::MyFunction(Stora

我正在使用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(但是除了在includes中提供WinRT之外,我无法在项目或设置中找到检查该问题的位置).

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

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

C++/CX
< C++ C++ C++ C++代码> < p>参见

代码使用c++/cx或c++/CLI,而不是c++/WrRT(它确实符合C++,不像其他)。如果设置了编译器选项,则使用的是C++/CX。否则你就使用C++了。虽然你不得不问你使用的是哪种编程语言,这很令人担忧。@I尽管我很感激你的帮助,但阴影并没有太大帮助。据我所知,我使用的语言是C++。这是我看到的“/ZW”中的“使用Windows运行时扩展”选项吗?谢谢你,Chuck。使用临时文件当然解决了我明确的问题,而且似乎很好地解决了潜在的问题。所以我大概是在尝试使用应用程序没有权限打开的文件(在本例中,该文件肯定在磁盘上)?再次感谢!
#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();
...
            }
        });
    }
});