HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpCritical

How do I use OpenFileDialog to select a folder?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howopenfiledialogusefolderselect

Problem

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.

Edit (by HC): march 2026 I noticed that the name of the package does not contain a dot after Microsoft, but a minus sign
So it should be: 'Microsoft-WindowsAPICodePack-Shell

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);
}

Code Snippets

Install-Package Microsoft.WindowsAPICodePack-Shell
using Microsoft.WindowsAPICodePack.Dialogs;
CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.InitialDirectory = "C:\\Users";
dialog.IsFolderPicker = true;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
    MessageBox.Show("You selected: " + dialog.FileName);
}

Context

Stack Overflow Q#11624298, score: 492

Revisions (0)

No revisions yet.