wpfexplorerwebview2maui-blazorblazor-desktop

.net Blazor Desktop folder picker?


I am using a WPF Desktop app with BlazorWebView. I would like to open up file explorer and have the user select a folder to get the path selected. I can use the browser input to select files but as I understand it is a limitation of the browser to allow me to select a folder path. Is there a Folder Picker for native access?

The Process.Start only seem to open the file explorer and won't let me choose the folder.

<blazor:BlazorWebView HostPage="wwwroot\index.html" Services="{DynamicResource services}">
            <blazor:BlazorWebView.RootComponents>
                <blazor:RootComponent Selector="#app" ComponentType="{x:Type shared:App}" />
            </blazor:BlazorWebView.RootComponents>
        </blazor:BlazorWebView>
@using System.Diagnostics


<button @onclick="OnClickOpenNativeFileExplorer">Open</button>

@code {
    private void OnClickOpenNativeFileExplorer(MouseEventArgs e)
    {
        Process.Start("explorer.exe");
    }
}


Solution

  • For anyone wondering, I was able to solve it by doing the following.

    I added the IFolderPicker interface to my razor class library. Then implement the FolderPicker in the WPF project using a NuGet package.

    Install-Package WindowsAPICodePack-Shell -Version 1.1.1
    
    public interface IFolderPicker
    {
        public string DisplayFolderPicker();
    }
    
    public class FolderPicker : IFolderPicker
    {
            public string DisplayFolderPicker()
            {
                var dialog = new CommonOpenFileDialog();
                dialog.IsFolderPicker = true;
                CommonFileDialogResult result = dialog.ShowDialog();
                if (result == CommonFileDialogResult.Ok)
                    return dialog.FileName;
                return "";
            }
    }
    

    I then register the dependency using the DI container within the MainWindow.xaml.cs file.

    public MainWindow()
            {
                InitializeComponent();
    
                Application.Current.MainWindow.WindowState = WindowState.Maximized;
    
                var serviceCollection = new ServiceCollection();
                serviceCollection.AddWpfBlazorWebView();
    
                serviceCollection.AddTransient<IFolderPicker, FolderPicker>();
    
                Resources.Add("services", serviceCollection.BuildServiceProvider());
            }
    

    Then within the razor component, I have a button that calls the DisplayFolderPicker method.

    @inject IFolderPicker _folderPicker
    
    
    <button @onclick="OnClickOpenNativeFileExplorer">Open</button>
    <p>@path</p>
    
    @code {
        private string path = "";
        private void OnClickOpenNativeFileExplorer(MouseEventArgs e)
        {
            path = _folderPicker.DisplayFolderPicker();
    
        }
    }
    

    Take-away: I suppose not only will this work for FolderPicker but for calling any native component.