Find a directory in C #

How can I present a control to a user that allows him / her to select a directory?

It seems that there aren't any .net controls built in?

+49
c #
Aug 14 '08 at 23:18
source share
7 answers

the FolderBrowserDialog class is the best option.

+52
Aug 14 '08 at 23:25
source share
string folderPath = ""; FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog(); if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) { folderPath = folderBrowserDialog1.SelectedPath ; } 
+70
Oct 03 2018-11-11T00:
source share

Note: There is no guarantee that this code will work in future versions of the .NET Framework. Using .Net private internal infrastructures, as done through reflection, is probably not very good. Use the middleware mentioned below, as the Windows API is less likely to change.

If you are looking for a folder picker that looks more like a Windows 7 dialog box, with the ability to copy and paste from the text box at the bottom and the navigation bar on the left with your favorite and usual places, you can access it in a very easy way.

FolderBrowserDialog's user interface is very minimal:

enter image description here

But you can use this instead:

enter image description here

Here's a class that opens a Vista-style folder collector using the .Net private IFileDialog , without directly using code interactions (.Net will take care of this for you). It returns to the pre-Vista dialog, if not on a high enough version of Windows. It should work in Windows 7, 8, 9, 10 and higher (theoretically).

 using System; using System.Reflection; using System.Windows.Forms; namespace MyCoolCompany.Shuriken { /// <summary> /// Present the Windows Vista-style open file dialog to select a folder. Fall back for older Windows Versions /// </summary> public class FolderSelectDialog { private string _initialDirectory; private string _title; private string _fileName = ""; public string InitialDirectory { get { return string.IsNullOrEmpty(_initialDirectory) ? Environment.CurrentDirectory : _initialDirectory; } set { _initialDirectory = value; } } public string Title { get { return _title ?? "Select a folder"; } set { _title = value; } } public string FileName { get { return _fileName; } } public bool Show() { return Show(IntPtr.Zero); } /// <param name="hWndOwner">Handle of the control or window to be the parent of the file dialog</param> /// <returns>true if the user clicks OK</returns> public bool Show(IntPtr hWndOwner) { var result = Environment.OSVersion.Version.Major >= 6 ? VistaDialog.Show(hWndOwner, InitialDirectory, Title) : ShowXpDialog(hWndOwner, InitialDirectory, Title); _fileName = result.FileName; return result.Result; } private struct ShowDialogResult { public bool Result { get; set; } public string FileName { get; set; } } private static ShowDialogResult ShowXpDialog(IntPtr ownerHandle, string initialDirectory, string title) { var folderBrowserDialog = new FolderBrowserDialog { Description = title, SelectedPath = initialDirectory, ShowNewFolderButton = false }; var dialogResult = new ShowDialogResult(); if (folderBrowserDialog.ShowDialog(new WindowWrapper(ownerHandle)) == DialogResult.OK) { dialogResult.Result = true; dialogResult.FileName = folderBrowserDialog.SelectedPath; } return dialogResult; } private static class VistaDialog { private const string c_foldersFilter = "Folders|\n"; private const BindingFlags c_flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; private readonly static Assembly s_windowsFormsAssembly = typeof(FileDialog).Assembly; private readonly static Type s_iFileDialogType = s_windowsFormsAssembly.GetType("System.Windows.Forms.FileDialogNative+IFileDialog"); private readonly static MethodInfo s_createVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("CreateVistaDialog", c_flags); private readonly static MethodInfo s_onBeforeVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("OnBeforeVistaDialog", c_flags); private readonly static MethodInfo s_getOptionsMethodInfo = typeof(FileDialog).GetMethod("GetOptions", c_flags); private readonly static MethodInfo s_setOptionsMethodInfo = s_iFileDialogType.GetMethod("SetOptions", c_flags); private readonly static uint s_fosPickFoldersBitFlag = (uint) s_windowsFormsAssembly .GetType("System.Windows.Forms.FileDialogNative+FOS") .GetField("FOS_PICKFOLDERS") .GetValue(null); private readonly static ConstructorInfo s_vistaDialogEventsConstructorInfo = s_windowsFormsAssembly .GetType("System.Windows.Forms.FileDialog+VistaDialogEvents") .GetConstructor(c_flags, null, new[] { typeof(FileDialog) }, null); private readonly static MethodInfo s_adviseMethodInfo = s_iFileDialogType.GetMethod("Advise"); private readonly static MethodInfo s_unAdviseMethodInfo = s_iFileDialogType.GetMethod("Unadvise"); private readonly static MethodInfo s_showMethodInfo = s_iFileDialogType.GetMethod("Show"); public static ShowDialogResult Show(IntPtr ownerHandle, string initialDirectory, string title) { var openFileDialog = new OpenFileDialog { AddExtension = false, CheckFileExists = false, DereferenceLinks = true, Filter = c_foldersFilter, InitialDirectory = initialDirectory, Multiselect = false, Title = title }; var iFileDialog = s_createVistaDialogMethodInfo.Invoke(openFileDialog, new object[] { }); s_onBeforeVistaDialogMethodInfo.Invoke(openFileDialog, new[] { iFileDialog }); s_setOptionsMethodInfo.Invoke(iFileDialog, new object[] { (uint) s_getOptionsMethodInfo.Invoke(openFileDialog, new object[] { }) | s_fosPickFoldersBitFlag }); var adviseParametersWithOutputConnectionToken = new[] { s_vistaDialogEventsConstructorInfo.Invoke(new object[] { openFileDialog }), 0U }; s_adviseMethodInfo.Invoke(iFileDialog, adviseParametersWithOutputConnectionToken); try { int retVal = (int) s_showMethodInfo.Invoke(iFileDialog, new object[] { ownerHandle }); return new ShowDialogResult { Result = retVal == 0, FileName = openFileDialog.FileName }; } finally { s_unAdviseMethodInfo.Invoke(iFileDialog, new[] { adviseParametersWithOutputConnectionToken[1] }); } } } // Wrap an IWin32Window around an IntPtr private class WindowWrapper : IWin32Window { private readonly IntPtr _handle; public WindowWrapper(IntPtr handle) { _handle = handle; } public IntPtr Handle { get { return _handle; } } } } } 

I designed this as a cleaned version . In the Bill Win Seddon -style NET Win 7 folder selection dialog box from lyquidity.com (I have no affiliation). I wrote my own because to solve it, it requires an additional Reflection class, which is not needed for this purposeful purpose, uses exception-based flow control, and does not cache the results of its reflection calls. Note that the VistaDialog nested static class is such that its static reflection variables do not attempt to populate if the Show method is never called.

It is used in the form of Windows:

 var dialog = new FolderSelectDialog { InitialDirectory = musicFolderTextBox.Text, Title = "Select a folder to import music from" }; if (dialog.Show(Handle)) { musicFolderTextBox.Text = dialog.FileName; } 

You can, of course, play with your options and the properties that it provides. For example, it allows multitasking in a Vista-style dialog box.

Also, note that Simon Murray gave an answer that showed how to do the same job using interop against the Windows API directly, although its version would have to be augmented to use the old dialogue style, if on the old version of Windows. Unfortunately, I have not yet found his message when I decided my decision. Name your poison!

+7
Nov 20 '15 at 0:39
source share

You can simply use the FolderBrowserDialog class from the System.Windows.Forms .

+5
Aug 14 '08 at 23:32
source share

Please do not try to use your own TreeView / DirectoryInfo class. On the one hand, there are many nice features that you get for free (icons / right-click / network) with SHBrowseForFolder. For another, there are edges / catches that you probably won't know.

+1
Aug 15 '08 at 0:03
source share

You can use TreeView in conjunction with the DirectoryInfo class.

0
Aug 14 '08 at 23:22
source share

For more functionality than FolderBrowserdialog, such as filtering, checkboxes, etc., look at third-party controls such as Shell MegaPack , because they are controls, so you can put them in your own forms and not appear as a modal dialog .

0
Jan 03 '09 at 10:48
source share



All Articles