Introduction
This code demonstrates a way to use the managed FileOpenDialog
control (available in .NET 2.0+) to open either a file or a folder from within the same dialog.
Background
For my Open-Source project, I was looking for a control that would allow users to select either a file or a folder from within the same dialog. Having searched the web, I came across a few solutions (one involving calling non-managed code, and one involving a custom-written control). Unfortunately, both solutions didn't work for me. The first one used the FolderSelect dialog (which is pretty inconvenient compared to the FileOpen dialog), and the second one did not provide 100% of the Windows dialog functionality.
I then decided to look into the source code of the WinMerge utility to see how they implemented similar functionality in C++ (and potentially used some native calls). It turned out that the solution was available right inside the .NET framework.
Using the code
The key to getting OpenFileDialog
to select both files and folders is to set the ValidateNames
and CheckFileExists
properties to false
(dialog.ValidateNames = false; dialog.CheckFileExists = false
) and set FileName
to some special keyword to make sure that folders get selected (dialog.FileName = "Folder Selection";
).
dialog.ValidateNames = false;
dialog.CheckFileExists = false;
dialog.CheckPathExists = true;
...
dialog.FileName = "Folder Selection.";
For convenience, I have wrapped OpenFileDialog
inside a custom class, FileFolderDialog
, and have also added a few helper properties to parse the returned file name.
History
- 11/25/2009 - First version of the article published.
- 11/30/2009 - Updated code to work with Windows 7.