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

<p>There doesn't seem to be any native .net controls which do this?</p>

[{'answer_id': 11775, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 7, 'selected': True, 'text': '<p>The <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog.aspx" rel="noreferrer">FolderBrowserDialog class</a> is the best option.</p>\n'}, {'answer_id': 11781, 'author': 'David Wengier', 'author_id': 489, 'author_profile': 'https://Stackoverflow.com/users/489', 'pm_score': 3, 'selected': False, 'text': '<p>You could just use the <code>FolderBrowserDialog</code> class from the <code>System.Windows.Forms</code> namespace.</p>\n'}, {'answer_id': 11800, 'author': 'Andrew Grant', 'author_id': 1043, 'author_profile': 'https://Stackoverflow.com/users/1043', 'pm_score': 1, 'selected': False, 'text': "<p>Please don't try and roll your own with a TreeView/DirectoryInfo class. For one thing there are many nice features you get for free (icons/right-click/networks) by using SHBrowseForFolder. For another there are a edge cases/catches you will likely not be aware of.</p>\n"}, {'answer_id': 7634179, 'author': 'Chandima', 'author_id': 976547, 'author_profile': 'https://Stackoverflow.com/users/976547', 'pm_score': 6, 'selected': False, 'text': '<pre><code>string folderPath = "";\nFolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();\nif (folderBrowserDialog1.ShowDialog() == DialogResult.OK) {\n    folderPath = folderBrowserDialog1.SelectedPath ;\n}\n</code></pre>\n'}, {'answer_id': 33817043, 'author': 'ErikE', 'author_id': 57611, 'author_profile': 'https://Stackoverflow.com/users/57611', 'pm_score': 5, 'selected': False, 'text': '<p><sup><sub><em>Note: there is no guarantee this code will work in future versions of the .Net framework. Using private .Net framework internals as done here through reflection is probably not good overall. Use the interop solution mentioned at the bottom, as the Windows API is less likely to change.</em></sub></sup></p>\n\n<p>If you are looking for a Folder picker that looks more like the Windows 7 dialog, with the ability to copy and paste from a textbox at the bottom and the navigation pane on the left with favorites and common locations, then you can get access to that in a very lightweight way.</p>\n\n<p>The FolderBrowserDialog UI is very minimal:</p>\n\n<p><a href="https://i.stack.imgur.com/T5qBb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/T5qBb.png" alt="enter image description here"></a></p>\n\n<p>But you can have this instead:</p>\n\n<p><a href="https://i.stack.imgur.com/T95kd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/T95kd.png" alt="enter image description here"></a></p>\n\n<p>Here\'s a class that opens a Vista-style folder picker using the .Net private <code>IFileDialog</code> interface, without directly using interop in the code (.Net takes care of that for you). It falls back to the pre-Vista dialog if not in a high enough Windows version. Should work in Windows 7, 8, 9, 10 and higher (theoretically).</p>\n\n<pre><code>using System;\nusing System.Reflection;\nusing System.Windows.Forms;\n\nnamespace MyCoolCompany.Shuriken {\n    /// &lt;summary&gt;\n    /// Present the Windows Vista-style open file dialog to select a folder. Fall back for older Windows Versions\n    /// &lt;/summary&gt;\n    public class FolderSelectDialog {\n        private string _initialDirectory;\n        private string _title;\n        private string _fileName = "";\n\n        public string InitialDirectory {\n            get { return string.IsNullOrEmpty(_initialDirectory) ? Environment.CurrentDirectory : _initialDirectory; }\n            set { _initialDirectory = value; }\n        }\n        public string Title {\n            get { return _title ?? "Select a folder"; }\n            set { _title = value; }\n        }\n        public string FileName { get { return _fileName; } }\n\n        public bool Show() { return Show(IntPtr.Zero); }\n\n        /// &lt;param name="hWndOwner"&gt;Handle of the control or window to be the parent of the file dialog&lt;/param&gt;\n        /// &lt;returns&gt;true if the user clicks OK&lt;/returns&gt;\n        public bool Show(IntPtr hWndOwner) {\n            var result = Environment.OSVersion.Version.Major &gt;= 6\n                ? VistaDialog.Show(hWndOwner, InitialDirectory, Title)\n                : ShowXpDialog(hWndOwner, InitialDirectory, Title);\n            _fileName = result.FileName;\n            return result.Result;\n        }\n\n        private struct ShowDialogResult {\n            public bool Result { get; set; }\n            public string FileName { get; set; }\n        }\n\n        private static ShowDialogResult ShowXpDialog(IntPtr ownerHandle, string initialDirectory, string title) {\n            var folderBrowserDialog = new FolderBrowserDialog {\n                Description = title,\n                SelectedPath = initialDirectory,\n                ShowNewFolderButton = false\n            };\n            var dialogResult = new ShowDialogResult();\n            if (folderBrowserDialog.ShowDialog(new WindowWrapper(ownerHandle)) == DialogResult.OK) {\n                dialogResult.Result = true;\n                dialogResult.FileName = folderBrowserDialog.SelectedPath;\n            }\n            return dialogResult;\n        }\n\n        private static class VistaDialog {\n            private const string c_foldersFilter = "Folders|\\n";\n\n            private const BindingFlags c_flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;\n            private readonly static Assembly s_windowsFormsAssembly = typeof(FileDialog).Assembly;\n            private readonly static Type s_iFileDialogType = s_windowsFormsAssembly.GetType("System.Windows.Forms.FileDialogNative+IFileDialog");\n            private readonly static MethodInfo s_createVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("CreateVistaDialog", c_flags);\n            private readonly static MethodInfo s_onBeforeVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("OnBeforeVistaDialog", c_flags);\n            private readonly static MethodInfo s_getOptionsMethodInfo = typeof(FileDialog).GetMethod("GetOptions", c_flags);\n            private readonly static MethodInfo s_setOptionsMethodInfo = s_iFileDialogType.GetMethod("SetOptions", c_flags);\n            private readonly static uint s_fosPickFoldersBitFlag = (uint) s_windowsFormsAssembly\n                .GetType("System.Windows.Forms.FileDialogNative+FOS")\n                .GetField("FOS_PICKFOLDERS")\n                .GetValue(null);\n            private readonly static ConstructorInfo s_vistaDialogEventsConstructorInfo = s_windowsFormsAssembly\n                .GetType("System.Windows.Forms.FileDialog+VistaDialogEvents")\n                .GetConstructor(c_flags, null, new[] { typeof(FileDialog) }, null);\n            private readonly static MethodInfo s_adviseMethodInfo = s_iFileDialogType.GetMethod("Advise");\n            private readonly static MethodInfo s_unAdviseMethodInfo = s_iFileDialogType.GetMethod("Unadvise");\n            private readonly static MethodInfo s_showMethodInfo = s_iFileDialogType.GetMethod("Show");\n\n            public static ShowDialogResult Show(IntPtr ownerHandle, string initialDirectory, string title) {\n                var openFileDialog = new OpenFileDialog {\n                    AddExtension = false,\n                    CheckFileExists = false,\n                    DereferenceLinks = true,\n                    Filter = c_foldersFilter,\n                    InitialDirectory = initialDirectory,\n                    Multiselect = false,\n                    Title = title\n                };\n\n                var iFileDialog = s_createVistaDialogMethodInfo.Invoke(openFileDialog, new object[] { });\n                s_onBeforeVistaDialogMethodInfo.Invoke(openFileDialog, new[] { iFileDialog });\n                s_setOptionsMethodInfo.Invoke(iFileDialog, new object[] { (uint) s_getOptionsMethodInfo.Invoke(openFileDialog, new object[] { }) | s_fosPickFoldersBitFlag });\n                var adviseParametersWithOutputConnectionToken = new[] { s_vistaDialogEventsConstructorInfo.Invoke(new object[] { openFileDialog }), 0U };\n                s_adviseMethodInfo.Invoke(iFileDialog, adviseParametersWithOutputConnectionToken);\n\n                try {\n                    int retVal = (int) s_showMethodInfo.Invoke(iFileDialog, new object[] { ownerHandle });\n                    return new ShowDialogResult {\n                        Result = retVal == 0,\n                        FileName = openFileDialog.FileName\n                    };\n                }\n                finally {\n                    s_unAdviseMethodInfo.Invoke(iFileDialog, new[] { adviseParametersWithOutputConnectionToken[1] });\n                }\n            }\n        }\n\n        // Wrap an IWin32Window around an IntPtr\n        private class WindowWrapper : IWin32Window {\n            private readonly IntPtr _handle;\n            public WindowWrapper(IntPtr handle) { _handle = handle; }\n            public IntPtr Handle { get { return _handle; } }\n        }\n    }\n}\n</code></pre>\n\n<p>I developed this as a cleaned up version of <a href="http://www.lyquidity.com/devblog/?p=136" rel="noreferrer">.NET Win 7-style folder select dialog</a> by Bill Seddon of <a href="http://lyquidity.com" rel="noreferrer">lyquidity.com</a> (I have no affiliation). I wrote my own because his solution requires an additional Reflection class that isn\'t needed for this focused purpose, uses exception-based flow control, doesn\'t cache the results of its reflection calls. Note that the nested static <code>VistaDialog</code> class is so that its static reflection variables don\'t try to get populated if the <code>Show</code> method is never called.</p>\n\n<p>It is used like so in a Windows Form:</p>\n\n<pre><code>var dialog = new FolderSelectDialog {\n    InitialDirectory = musicFolderTextBox.Text,\n    Title = "Select a folder to import music from"\n};\nif (dialog.Show(Handle)) {\n    musicFolderTextBox.Text = dialog.FileName;\n}\n</code></pre>\n\n<p>You can of course play around with its options and what properties it exposes. For example, it allows multiselect in the Vista-style dialog.</p>\n\n<p>Also, please note that <a href="https://stackoverflow.com/a/15386992/57611">Simon Mourier gave an answer</a> that shows how to do the exact same job using interop against the Windows API directly, though his version would have to be supplemented to use the older style dialog if in an older version of Windows. Unfortunately, I hadn\'t found his post yet when I worked up my solution. Name your poison!</p>\n'}, {'answer_id': 50002970, 'author': 'Smith', 'author_id': 362461, 'author_profile': 'https://Stackoverflow.com/users/362461', 'pm_score': 0, 'selected': False, 'text': '<p>or even more better, you can put this code in a class file</p>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\ninternal class OpenFolderDialog : IDisposable {\n\n    /// &lt;summary&gt;\n    /// Gets/sets folder in which dialog will be open.\n    /// &lt;/summary&gt;\n    public string InitialFolder { get; set; }\n\n    /// &lt;summary&gt;\n    /// Gets/sets directory in which dialog will be open if there is no recent directory available.\n    /// &lt;/summary&gt;\n    public string DefaultFolder { get; set; }\n\n    /// &lt;summary&gt;\n    /// Gets selected folder.\n    /// &lt;/summary&gt;\n    public string Folder { get; private set; }\n\n\n    internal DialogResult ShowDialog(IWin32Window owner) {\n        if (Environment.OSVersion.Version.Major &gt;= 6) {\n            return ShowVistaDialog(owner);\n        } else {\n            return ShowLegacyDialog(owner);\n        }\n    }\n\n    private DialogResult ShowVistaDialog(IWin32Window owner) {\n        var frm = (NativeMethods.IFileDialog)(new NativeMethods.FileOpenDialogRCW());\n        uint options;\n        frm.GetOptions(out options);\n        options |= NativeMethods.FOS_PICKFOLDERS | NativeMethods.FOS_FORCEFILESYSTEM | NativeMethods.FOS_NOVALIDATE | NativeMethods.FOS_NOTESTFILECREATE | NativeMethods.FOS_DONTADDTORECENT;\n        frm.SetOptions(options);\n        if (this.InitialFolder != null) {\n            NativeMethods.IShellItem directoryShellItem;\n            var riid = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"); //IShellItem\n            if (NativeMethods.SHCreateItemFromParsingName(this.InitialFolder, IntPtr.Zero, ref riid, out directoryShellItem) == NativeMethods.S_OK) {\n                frm.SetFolder(directoryShellItem);\n            }\n        }\n        if (this.DefaultFolder != null) {\n            NativeMethods.IShellItem directoryShellItem;\n            var riid = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"); //IShellItem\n            if (NativeMethods.SHCreateItemFromParsingName(this.DefaultFolder, IntPtr.Zero, ref riid, out directoryShellItem) == NativeMethods.S_OK) {\n                frm.SetDefaultFolder(directoryShellItem);\n            }\n        }\n\n        if (frm.Show(owner.Handle) == NativeMethods.S_OK) {\n            NativeMethods.IShellItem shellItem;\n            if (frm.GetResult(out shellItem) == NativeMethods.S_OK) {\n                IntPtr pszString;\n                if (shellItem.GetDisplayName(NativeMethods.SIGDN_FILESYSPATH, out pszString) == NativeMethods.S_OK) {\n                    if (pszString != IntPtr.Zero) {\n                        try {\n                            this.Folder = Marshal.PtrToStringAuto(pszString);\n                            return DialogResult.OK;\n                        } finally {\n                            Marshal.FreeCoTaskMem(pszString);\n                        }\n                    }\n                }\n            }\n        }\n        return DialogResult.Cancel;\n    }\n\n    private DialogResult ShowLegacyDialog(IWin32Window owner) {\n        using (var frm = new SaveFileDialog()) {\n            frm.CheckFileExists = false;\n            frm.CheckPathExists = true;\n            frm.CreatePrompt = false;\n            frm.Filter = "|" + Guid.Empty.ToString();\n            frm.FileName = "any";\n            if (this.InitialFolder != null) { frm.InitialDirectory = this.InitialFolder; }\n            frm.OverwritePrompt = false;\n            frm.Title = "Select Folder";\n            frm.ValidateNames = false;\n            if (frm.ShowDialog(owner) == DialogResult.OK) {\n                this.Folder = Path.GetDirectoryName(frm.FileName);\n                return DialogResult.OK;\n            } else {\n                return DialogResult.Cancel;\n            }\n        }\n    }\n\n\n    public void Dispose() { } //just to have possibility of Using statement.\n\n}\n\ninternal static class NativeMethods {\n\n    #region Constants\n\n    public const uint FOS_PICKFOLDERS = 0x00000020;\n    public const uint FOS_FORCEFILESYSTEM = 0x00000040;\n    public const uint FOS_NOVALIDATE = 0x00000100;\n    public const uint FOS_NOTESTFILECREATE = 0x00010000;\n    public const uint FOS_DONTADDTORECENT = 0x02000000;\n\n    public const uint S_OK = 0x0000;\n\n    public const uint SIGDN_FILESYSPATH = 0x80058000;\n\n    #endregion\n\n\n    #region COM\n\n    [ComImport, ClassInterface(ClassInterfaceType.None), TypeLibType(TypeLibTypeFlags.FCanCreate), Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")]\n    internal class FileOpenDialogRCW { }\n\n\n    [ComImport(), Guid("42F85136-DB7E-439C-85F1-E4075D135FC8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\n    internal interface IFileDialog {\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        [PreserveSig()]\n        uint Show([In, Optional] IntPtr hwndOwner); //IModalWindow \n\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint SetFileTypes([In] uint cFileTypes, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr rgFilterSpec);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint SetFileTypeIndex([In] uint iFileType);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint GetFileTypeIndex(out uint piFileType);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint Advise([In, MarshalAs(UnmanagedType.Interface)] IntPtr pfde, out uint pdwCookie);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint Unadvise([In] uint dwCookie);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint SetOptions([In] uint fos);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint GetOptions(out uint fos);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        void SetDefaultFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint SetFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint GetFolder([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint GetCurrentSelection([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint SetFileName([In, MarshalAs(UnmanagedType.LPWStr)] string pszName);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint SetTitle([In, MarshalAs(UnmanagedType.LPWStr)] string pszTitle);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint SetOkButtonLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszText);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint SetFileNameLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint GetResult([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint AddPlace([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, uint fdap);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint SetDefaultExtension([In, MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint Close([MarshalAs(UnmanagedType.Error)] uint hr);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint SetClientGuid([In] ref Guid guid);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint ClearClientData();\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint SetFilter([MarshalAs(UnmanagedType.Interface)] IntPtr pFilter);\n    }\n\n\n    [ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\n    internal interface IShellItem {\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint BindToHandler([In] IntPtr pbc, [In] ref Guid rbhid, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IntPtr ppvOut);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint GetParent([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint GetDisplayName([In] uint sigdnName, out IntPtr ppszName);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint GetAttributes([In] uint sfgaoMask, out uint psfgaoAttribs);\n\n        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n        uint Compare([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, [In] uint hint, out int piOrder);\n    }\n\n    #endregion\n\n\n    [DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)]\n    internal static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IntPtr pbc, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppv);\n\n}\n</code></pre>\n\n<p>And use it like this</p>\n\n<pre><code>using (var frm = new OpenFolderDialog()) {\n                if (frm.ShowDialog(this)== DialogResult.OK) {\n                    MessageBox.Show(this, frm.Folder);\n                }\n            }\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/11767', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/234/']