Search code examples
c#asynchronousuwpfilepicker

C# UWP - How do I fix the FileOpenPicker and StorageFile async error?


I am learning UWP, and am more familiar with Windows.Forms.

I have two buttons to upload files through my application to the server (btnUploadPrice is one of the two). To get the existing location of the file and store that info, i looked up how things are different in UWP compared to the Windows.Forms style and used these Microsoft pages as a template: https://learn.microsoft.com/en-us/uwp/api/windows.storage.storagefile https://learn.microsoft.com/en-us/uwp/api/Windows.Storage.Pickers.FileOpenPicker

Here is my button code:

private void btnUploadPrice_Click(object sender, RoutedEventArgs e)
{
    //open file dialog and store name until save button pressed.
    FileOpenPicker f = new FileOpenPicker();
    StorageFile price = await f.PickSingleFileAsync();
    f.SuggestedStartLocation = PickerLocationId.Desktop;
    f.ViewMode = PickerViewMode.Thumbnail;
    if (price != null)
    {
        // Store file for future access
        Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(price);
    }
}

await f.PickSingleFileAsync() is underlined with the following error: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

My issue is that this is almost a copy/paste from Microsoft, and it's giving me an error that doesn't make sense, because it is an Async method, it says it right in the name of the method.. PickSingleFileAsync

What am i missing?


Solution

  • await can only be used inside an async method. Just change your method signature to make it async:

    private async void btnUploadPrice_Click(object sender, RoutedEventArgs e)
    {
        // your code
    }