can not get folder?

mc 3,641 Reputation points
2022-09-28T00:52:13.003+00:00
var folder = new FolderPicker();  
  
            var path = await folder.PickSingleFolderAsync();  

it is not work.

Universal Windows Platform (UWP)
Windows App SDK
Windows App SDK
A set of Microsoft open-source libraries, frameworks, components, and tools to be used in apps to access Windows platform functionality on many versions of Windows. Previously known as Project Reunion.
722 questions
0 comments No comments
{count} votes

Accepted answer
  1. Roy Li - MSFT 31,551 Reputation points Microsoft Vendor
    2022-09-28T02:24:38.163+00:00

    Hello,

    Welcome to Microsoft Q&A!

    The FileOpenPicker, FileSavePicker, and FolderPicker APIs require an HWND associated with them so that they know which window is the target window they need to show over. If you are trying to use FolderPicker in a WinUI3 application, you will need to get the current HWND and set the HWND on the picker.

    Like this:

            var Picker = new FolderPicker();  
    
            // Get the current window's HWND by passing in the Window object  
            var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(this);  
    
            // Associate the HWND with the file picker  
            WinRT.Interop.InitializeWithWindow.Initialize(Picker, hwnd);  
    
            Picker.FileTypeFilter.Add("*");  
    
            var folder = await Picker.PickSingleFolderAsync();  
    

    Thank you.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Tony Brummel 1 Reputation point
    2022-12-30T03:05:18.047+00:00

    For anyone who may be trying to use FolderPicker after calling InitializeWithWindow (as I was) and is still getting an exception:

    You MUST set a FileTypeFilter as shown above or the FolderPicker will throw an exception. I'm assuming this is a bug as it's not documented as a property that must be set (and the exception type would be something better if it were by design).

    Note: for a C# WinUI3 app (not packaged) - WindowsAppSDK 1.2.221209.1

    0 comments No comments