Search code examples
uwpc++-cxfilepicker

UWP, C++/Cx FileOpenPicker


Does anyone know what I'm doing wrong with this.

    // STORAGE FILE
    StorageFile^ saveFile;

    // FILE PICKER, FOR SELECTING A SAVE FILE
    FileOpenPicker^ filePicker = ref new FileOpenPicker;

    // ARRAY OF FILE TYPES
    Array<String^>^ fileTypes = ref new Array<String^>(1);
    fileTypes->Data[0] = ".txt";

    filePicker->ViewMode = PickerViewMode::Thumbnail;
    filePicker->SuggestedStartLocation = PickerLocationId::Desktop;
    filePicker->FileTypeFilter->ReplaceAll(fileTypes);

    // THIS SHOULD HOPEFULLY LET US PICK A FILE

    saveFile = filePicker->PickSingleFileAsync();

specifically the last line:

saveFile = filePicker->PickSingleFileAsync();

I get the following error.

error C2440: '=': cannot convert from 'Windows::Foundation::IAsyncOperation ^' to 'Windows::Storage::StorageFile ^'


Solution

  • error C2440: '=': cannot convert from 'Windows::Foundation::IAsyncOperation ^' to 'Windows::Storage::StorageFile ^'

    PickSingleFileAsync is asynchronous method, and the return type is Windows::Foundation::IAsyncOperation,it can't be convert to StorageFile type. As Hans Passant said you could use create_task() to await this async operation.

    create_task(folderPicker->PickSingleFolderAsync()).then([this](StorageFolder^ folder)
    {
        if (folder)
        {
            //do some stuff
        }
        else
        {
            //do some stuff
        }
    });
    

    For more please refer to Asynchronous programming in C++.