使用FileOpenPicker时出现UnauthorizedAccessException

时间:2014-10-22 00:28:53

标签: c# .net windows windows-store-apps windows-store

我的Windows应用商店应用中有CommandBar,当我点击Open上的CommandBar按钮时,它运行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);
});

1 个答案:

答案 0 :(得分:0)

是的,这是由于RT的对话竞赛条件造成的。解决方案是让我字面使用MessageDialog类,就像在MessageBox.Show中使用WinForms一样:

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);
}