Search code examples
c#.netwinformsdialogopenfiledialog

How do I use OpenFileDialog to select a folder?


I was going to use the following project: https://github.com/scottwis/OpenFileOrFolderDialog

However, there's a problem: it uses the GetOpenFileName function and OPENFILENAME structure. OPENFILENAME has the member named templateID, which is the identifier for dialog template. And the project contains the res1.rc file and the templated dialog init, too. But I couldn't figure out how to attach this file to my C# project.

Is there a better way to use an OpenFileDialog to select folders?


Solution

  • As a note for future users who would like to avoid using FolderBrowserDialog, Microsoft once released an API called the WindowsAPICodePack that had a helpful dialog called CommonOpenFileDialog, that could be set into a IsFolderPicker mode. The API is available from Microsoft as a NuGet package.

    This is all I needed to install and use the CommonOpenFileDialog. (NuGet handled the dependencies)

    Install-Package Microsoft.WindowsAPICodePack-Shell
    

    For the include line:

    using Microsoft.WindowsAPICodePack.Dialogs;
    

    Usage:

    CommonOpenFileDialog dialog = new CommonOpenFileDialog();
    dialog.InitialDirectory = "C:\\Users";
    dialog.IsFolderPicker = true;
    if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
    {
        MessageBox.Show("You selected: " + dialog.FileName);
    }