如何在 WPF c# 桌面应用程序中使用 UWP FolderPicker

How to use UWP FolderPicker in a WPF c# desktop app

我有一个 WPF 桌面应用程序,我想使用 UWP FolderPicker API 选择一个目录。我的应用程序使用 UWP 打包项目,因此它被构建并 运行 作为一个 appx。我添加了 Windows 和 WindowsBase 引用,我的项目构建并运行。但是,在尝试使用文件夹选择器时出现运行时错误。我的代码如下:

    private async void OnGetDirectory(object parameter)
    {

        var folderPicker = new Windows.Storage.Pickers.FolderPicker();
        folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
        folderPicker.FileTypeFilter.Add("*");

        Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync();
        if (folder != null)
        {
            // Application now has read/write access to all contents in the picked folder
            // (including other sub-folder contents)
            Windows.Storage.AccessCache.StorageApplicationPermissions.
            FutureAccessList.AddOrReplace("PickedFolderToken", folder);
        }
        else
        {
        }
    }

我得到的错误在行 System.Exception: await folderPicker.PickSingleFolderAsync(); 和错误 'Invalid window handle. (Exception from HRESULT: 0x80070578)'

我错过了什么,或者甚至可以使用 WPF 应用程序中的 FolderPicker?

根据 UWP APIs available to a packaged desktop app (Desktop Bridge) 文章,某些功能区域尚未完全测试或目前未按预期运行。您刚刚在列表中使用的 "File and folder pickers" 功能。此功能的详细说明如下:

Packaged apps have full file system access and do not need UWP pickers.

因此 FolderPicker 可能无法在您的 UWP 打包项目中完成支持。请尝试使用WPF本身支持的文件相关API。

更多详情请参考this document

您可以使用普通的 Windows Forms 文件夹对话框代替 UWP FolderPicker - System.Windows.Forms 命名空间中的 FolderBrowserDialog(有关示例,请参见 this question ).

如果您想使用 StorageFolder,您可以调用 StorageFolder.GetFolderFromPathAsync 方法,或者您可以使用经典的文件夹 API,例如 System.IO.DirectorySystem.IO.DirectoryInfo.