What the hell is wrong with my code?

    private void BrowseButton_Click(object sender, RoutedEventArgs e)
    {
        FileOpenPicker FilePicker = new FileOpenPicker();
        FilePicker.FileTypeFilter.Add(".exe");
        FilePicker.ViewMode = PickerViewMode.List;
        FilePicker.SuggestedStartLocation = PickerLocationId.Desktop;
        // IF I PUT AWAIT HERE   V     I GET ANOTHER ERROR¹
        StorageFile file = FilePicker.PickSingleFileAsync();
        if (file != null)
        {
            AppPath.Text = file.Name;
        }
        else
        {
            AppPath.Text = "";
        }         
    }

It gives me this error:

Cannot implicitly convert type 'Windows.Foundation.IAsyncOperation' to 'Windows.Storage.StorageFile'

And if I add the 'await', like commented on the code, I get 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'.

Code source here

有帮助吗?

解决方案

Well, the reason your code doesn't compile is explained pretty directly by the compiler error message. FileOpenPicker.PickSingleFileAsync returns an IAsyncOperation<StorageFile> - so no, you can't assign that return value to a StorageFile variable. The typical way of using IAsyncOperation<> in C# is with await.

You can only use await in async methods... so you probably want to change your method to be asynchronous:

private async void BrowseButton_Click(object sender, RoutedEventArgs e)
{
    ...
    StorageFile file = await FilePicker.PickSingleFileAsync();
    ...
}

Note that for anything other than event handlers, it's better to make an async method return Task rather than void - the ability to use void is really only so you can use an async method as an event handler.

If you're not really familiar with async/await yet, you should probably read up on it before you go any further - the MSDN "Asynchronous Programming with async and await" page is probably a decent starting point.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top