从Winform迁移到UWP之后发现FileOpenDialog这个好用的控件不见了。查了Bing之后才知道在UWP中是用FileOpenPicker了。
下面这个就是微软的示例代码,但是放到我们UWP的事件函数中会报错 ”await 只能用于异步方法中,请考虑使用async修饰方法”
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".png");
Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
// Application now has read/write access to the picked file
this.textBlock.Text = "Picked photo: " + file.Name;
}
else
{
this.textBlock.Text = "Operation cancelled.";
}
报错位置在 “await”所在的行,这种用法我很陌生。捣鼓了半天也没有整通过。
private void PickAFileButton_Click(object sender, RoutedEventArgs e)
{
// Clear previous returned file name, if it exists, between iterations of this scenario
OutputTextBlock.Text = "";
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
// The StorageFile has read/write access to the picked file.
// See the FileAccess sample for code that uses a StorageFile to read and write.
OutputTextBlock.Text = "Picked photo: " + file.Name;
}
else
{
OutputTextBlock.Text = "Operation cancelled.";
}
}
后来找到了一份微软的SampleCode,才整明白。其实解决方法很简单,就像报错提示的一样。在事件函数前面加上“async”就可以了。
private async void PickAFileButton_Click(object sender, RoutedEventArgs e){
在示例代码中,我们看到获取文件名就直接调用 StorageFile.Name, 但是这个文件名是不包含完整路径的,包含完整路径的文件名是 StorageFile.Path.