OpenFolderDialog

 Posted by  Programming  Add comments  Tagged with:
Dec 312011
 

I hate FolderBrowserDialog. It is limited, ugly and stuck in Windows 2000 GUI. Whenever I had to select folder, I would resort to using SaveFileDialog instead. User would select any file name and I would just use directory part. It was non-optimal but still better than FolderBrowserDialog.

Vista brought new common file dialogs but I pretty much ignored them – most of my programs need to run under XP so there was not much benefit in using Windows Vista specific controls. However, those controls had special mode that finally brings folder selection in normal FileOpenDialog.

Code (after you define all needed COM interfaces) is actually quite straightforward. Once FOS_PICKFOLDERS is set, half of work is done. All other code is just plumbing to show the form and get user’s selection in form of path.

var frm = (IFileDialog)(new FileOpenDialogRCW());
uint options;
frm.GetOptions(out options);
options |= FOS_PICKFOLDERS;
frm.SetOptions(options);

if (frm.Show(owner.Handle) == S_OK) {
    IShellItem shellItem;
    frm.GetResult(out shellItem);
    IntPtr pszString;
    shellItem.GetDisplayName(SIGDN_FILESYSPATH, out pszString);
    this.Folder = Marshal.PtrToStringAuto(pszString);
}

Full code with Windows XP compatibility and little bit more error checking is available for download. However do notice that all unneeded COM fat has been trimmed in order to have it concise. Short and sweet I say.

[2012-02-12: Fixed bug in source code.]

  12 Responses to “OpenFolderDialog”

Comments (12)
  1. It crashes when you press cancel.

  2. what references do I need?

  3. Work fine! How to pick multifolder?

    • Added
      public const uint OFN_ALLOWMULTISELECT = 0×00000200;
      But failed in
      if (frm.GetResult(out shellItem) == NativeMethods.S_OK)

  4. Is there a vb.net version of this?

  5. Works good with Windows 7 but with XP it just opens the standard SaveFileDialog showing the box for the file name and even [Save] on the button.

    I thought this was supposed to work on XP too?

  6. What is the licensing for this code?

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>