Search code examples
c#wpfuwpdesktop-bridge

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


I have a WPF desktop app and I want to use the UWP FolderPicker API to pick a directory. My app uses the UWP packaging project so it is built and ran as an appx. I've added in the Windows and WindowsBase references and my project builds and runs. However I get a runtime error when trying to use the folder picker. My code is as follows:

    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
        {
        }
    }

The error I get is on the line System.Exception: await folderPicker.PickSingleFolderAsync(); and the error 'Invalid window handle. (Exception from HRESULT: 0x80070578)'

What am I missing or is it even possible to use the FolderPicker from a WPF app?


Solution

  • According to UWP APIs available to a packaged desktop app (Desktop Bridge) article, some feature areas are not yet fully tested or currently functioning as intended. The "File and folder pickers" feature that you used just in the list. The detail description for this feature is as follows:

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

    So that FolderPicker may not completed supported in your UWP packing project. Please try to use the file relative APIs that supported in WPF itself.

    More details please reference this document.