Skip to content

Instantly share code, notes, and snippets.

@mike-kilo
Created September 2, 2020 12:26
Show Gist options
  • Save mike-kilo/c2c19c7c0e26863926e65e735805c93c to your computer and use it in GitHub Desktop.
Save mike-kilo/c2c19c7c0e26863926e65e735805c93c to your computer and use it in GitHub Desktop.
Browse folder dialog [C#/.NET]
using System.IO;
using System.Windows;
namespace Snippets
{
public static class BrowseFolderDialog
{
public static string Show(Window owner, string caption, string startingLocation, bool withFileName)
{
string result = string.Empty;
System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
string resultFile = withFileName ? Path.GetFileName(startingLocation) : string.Empty;
dlg.SelectedPath = withFileName ? Path.GetDirectoryName(startingLocation) : startingLocation;
dlg.Description = caption;
dlg.ShowNewFolderButton = true;
System.Windows.Forms.IWin32Window win32Window = new System.Windows.Forms.NativeWindow();
((System.Windows.Forms.NativeWindow)win32Window).AssignHandle(new System.Windows.Interop.WindowInteropHelper(owner).Handle);
if (dlg.ShowDialog(win32Window) == System.Windows.Forms.DialogResult.OK)
{
result = Path.Combine(dlg.SelectedPath, resultFile);
}
return result;
}
}
}
@mike-kilo
Copy link
Author

A wrapper around the WindowsForms' FolderBrowserDialog - sets the defaults, allows for the initial location and sets whether the given path contains the filename as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment