使用FileOpenPicker时出现UnauthorizedAccessException
本文关键字:UnauthorizedAccessException FileOpenPicker 使用 | 更新日期: 2023-09-27 18:27:26
我的Windows应用商店应用程序中有一个CommandBar
,当我单击CommandBar
上的Open
按钮时,它会运行OpenFile
处理程序,如下所示:
private async void OpenFile(object sender, RoutedEventArgs e)
{
MessageDialog dialog = new MessageDialog("You are about to open a new file. Do you want to save your work first?");
dialog.Commands.Add(new UICommand("Yes", new UICommandInvokedHandler(SaveAndOpen)));
dialog.Commands.Add(new UICommand("No", new UICommandInvokedHandler(Open)));
await dialog.ShowAsync();
}
private async void SaveAndOpen(IUICommand command)
{
await SaveFile();
Open(command);
}
private async void Open(IUICommand command)
{
FileOpenPicker fileOpenPicker = new FileOpenPicker();
fileOpenPicker.ViewMode = PickerViewMode.List;
fileOpenPicker.FileTypeFilter.Add(".txt");
StorageFile file = await fileOpenPicker.PickSingleFileAsync();
await LoadFile(file);
}
我看到的消息很好,但只有当我点击Yes
时,我才会收到FileOpenPicker
。当我点击No
时,我在以下行得到一个UnauthorizedAccessException: Access is denied.
:StorageFile file = await fileOpenPicker.PickSingleFileAsync();
我很困惑。。。有人知道为什么会发生这种事吗?我甚至试着在一个调度器中运行它,以防处理程序在另一个线程上被调用,但是。。。不幸的是,同样的事情:
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
{
StorageFile file = await fileOpenPicker.PickSingleFileAsync();
await LoadFile(file);
});
是的,这是由于RT的对话框竞争条件。对我来说,解决方案是字面上使用MessageDialog
类,就像在WinForms
:中使用MessageBox.Show
一样
private async void OpenFile(object sender, RoutedEventArgs e)
{
MessageDialog dialog = new MessageDialog("You are about to open a new file. Do you want to save your work first?");
IUICommand result = null;
dialog.Commands.Add(new UICommand("Yes", (x) =>
{
result = x;
}));
dialog.Commands.Add(new UICommand("No", (x) =>
{
result = x;
}));
await dialog.ShowAsync();
if (result.Label == "Yes")
{
await SaveFile();
}
FileOpenPicker fileOpenPicker = new FileOpenPicker();
fileOpenPicker.ViewMode = PickerViewMode.List;
fileOpenPicker.FileTypeFilter.Add(".txt");
StorageFile file = await fileOpenPicker.PickSingleFileAsync();
await LoadFile(file);
}