C# – How to use OpenFileDialog to select a folder

cdialognetopenfiledialogwinforms

How to use OpenFileDialog to select folders?

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

However, I faced one problem. It uses the GetOpenFileName function and OPENFILENAME structure. And OPENFILENAME has the member named templateID. It's 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?

Best Answer

Basically you need the FolderBrowserDialog class:

Prompts the user to select a folder. This class cannot be inherited.

Example:

using(var fbd = new FolderBrowserDialog())
{
    DialogResult result = fbd.ShowDialog();

    if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
    {
        string[] files = Directory.GetFiles(fbd.SelectedPath);

        System.Windows.Forms.MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
    }
}

If you work in WPF you have to add the reference to System.Windows.Forms.

you also have to add using System.IO for Directory class