Handling an IAsyncOperation<StorageFile^>^ object in C++/CX

2

I want to create a file in the local folder, so I have written the following code:

IAsyncOperation<StorageFile^>^ fileTask = Windows::Storage::ApplicationData::Current->LocalFolder->CreateFileAsync("example.dat");

But how should I handle the fileTask? I have tried to call the GetResults-method, but then I get following exception:

Ausnahme ausgelöst bei 0x00007FFD211C7788 (KernelBase.dll) in Test.exe: 0x40080201: WinRT originate error (Parameter: 0x000000008000000E, 0x0000000000000040, 0x000000C00EBFC470).
Ausnahme ausgelöst bei 0x00007FFD211C7788 in Test.exe: Microsoft C++-Ausnahme: Platform::COMException ^ bei Speicherort 0x000000C00EBFC730. HRESULT:0x8000000E Eine Methode wurde zu einem unerwarteten Zeitpunkt aufgerufen.
WinRT-Informationen: Eine Methode wurde zu einem unerwarteten Zeitpunkt aufgerufen.

Next I have tried to use create_task:

create_task(Windows::Storage::ApplicationData::Current->LocalFolder->CreateFileAsync("example.dat")).then([this](StorageFile^ file)
{
    // irrelevant
});

Exception:

Ausnahme ausgelöst bei 0x00007FFD211C7788 (KernelBase.dll) in Test.exe: 0x40080201: WinRT originate error (Parameter: 0x00000000800700B7, 0x0000000000000048, 0x000000A936DFB230).
Ausnahme ausgelöst bei 0x00007FFD211C7788 (KernelBase.dll) in Test.exe: 0xE06D7363: Microsoft C++ Exception (Parameter: 0xCCCCCCCC19930520, 0x000000A936DFB830, 0x00007FFD01398AD0, 0x00007FFD012C0000).

Sorry for the language

How could I solve this Problem?

file
uwp
c++-cx

1 Answer

2

Next I have tried to use create_task...

You are in the correct direction. It is recommended to use task class for async operation.

But the file example.dat is probably already there when you call the GetResults. Thus you won't be able to use create_task(Windows::Storage::ApplicationData::Current->LocalFolder->CreateFileAsync("example.dat")).then([this](StorageFile^ file) to create the file again.

To fix the problem, just modify the codes like below:

#include <ppltasks.h>
create_task(Windows::Storage::ApplicationData::Current->LocalFolder->CreateFileAsync("example.dat", CreationCollisionOption::ReplaceExisting)).then([this](StorageFile^ file)
{

});

Added CreationCollisionOption::ReplaceExisting so that everytime the new file will replace the old file. And don't forget to include the ppltask.h.

answered on Stack Overflow Sep 15, 2016 by Elvis Xia - MSFT

User contributions licensed under CC BY-SA 3.0