I want the user to select a directory where a file that I will then generate will be saved. I know that in WPF I should use the OpenFileDialog
from Win32, but unfortunately the dialog requires file(s) to be selected - it stays open if I simply click OK without choosing one. I could "hack up" the functionality by letting the user pick a file and then strip the path to figure out which directory it belongs to but that's unintuitive at best. Has anyone seen this done before?
UPDATE 2023: Finally, with .NET 8, WPF gets a native, modern OpenFolderDialog
:
var folderDialog = new OpenFolderDialog
{
// Set options here
};
if (folderDialog.ShowDialog() == true)
{
var folderName = folderDialog.FolderName;
// Do something with the result
}
Does this mean that Microsoft finally invests resources in adding missing functionality to WPF? Of course not! Microsoft employees are busy enabling you to build cloud-native AI-based <insert more buzzwords here> Teams chat bots. Mundane tasks like fixing WPF to solve real-live, boring business needs are left to community volunteers like Jan, who added this folder browser dialog to .NET.
Old answer for .NET Framework 4.8:
You can use the built-in FolderBrowserDialog class for this. Don't mind that it's in the System.Windows.Forms
namespace.
using (var dialog = new System.Windows.Forms.FolderBrowserDialog())
{
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
}
If you want the window to be modal over some WPF window, see the question How to use a FolderBrowserDialog from a WPF application.
If you want something a bit more fancy than the plain, ugly Windows Forms FolderBrowserDialog, there are some alternatives that allow you to use the Vista dialog instead:
Third-party libraries, such as Ookii dialogs (.NET 4.5+)
The Windows API Code Pack-Shell:
using Microsoft.WindowsAPICodePack.Dialogs;
...
var dialog = new CommonOpenFileDialog();
dialog.IsFolderPicker = true;
CommonFileDialogResult result = dialog.ShowDialog();
Note that this dialog is not available on operating systems older than Windows Vista, so be sure to check CommonFileDialog.IsPlatformSupported
first.