Search code examples
vb.netfolderbrowserdialog

Setting root folder for FolderBrowser


How do i Set the root folder for a folderdialog?

My sample does not seem to work. (I checked that the folder exists)

    Dim FolderBrowserDialog1 As New FolderBrowserDialog

    FolderBrowserDialog1.RootFolder = "C:\VaultWorkspace\cadcampc\"

    If (FolderBrowserDialog1.ShowDialog() = DialogResult.OK) Then
        Copy_Design_New_Loc.Text = FolderBrowserDialog1.SelectedPath
    End If

Error message

An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll

Additional information: Conversion from string "C:\VaultWorkspace\cadcampc\" to type 'Integer' is not valid.

What do I need to do to set my custom location as rootfolder?


Solution

  • FolderBrowserDialog has always been a margin tool IMO.

    When opening a standard mapped folder you can use RootFolder to remove some clutter. SelectedPath will open the parent folder and highlight your folder but it may be off screen. Your posted path may look OK as it most likely has a small number of folders to display and the selected one should be visible.

        FolderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer
        FolderBrowserDialog1.SelectedPath = "C:\temp"
        If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            MsgBox(FolderBrowserDialog1.SelectedPath)
        End If
    

    Tested on Win7 .Net 4 VS2013 VB.Net WinForms


    Here's a variation that doesn't need the control on the form:

        Using fbd As New FolderBrowserDialog
            fbd.RootFolder = Environment.SpecialFolder.MyComputer
            fbd.SelectedPath = "H:\temp\scans"
            If fbd.ShowDialog = Windows.Forms.DialogResult.OK Then
                MsgBox(fbd.SelectedPath)
            End If
        End Using
    

    Here's a way to use the OpenFileDialog, far from perfect but better than folder dialog IMO, and simpler than a subclass:

        Using obj As New OpenFileDialog
            obj.Filter = "foldersOnly|*.none"
            obj.CheckFileExists = False
            obj.CheckPathExists = False
            obj.InitialDirectory = "C:\temp"
            obj.CustomPlaces.Add("H:\OIS") ' add your custom location, appears upper left
            obj.CustomPlaces.Add("H:\Permits") ' add your custom location
            obj.Title = "Select folder - click Open to return opened folder name"
            obj.FileName = "OpenFldrPath"
            If obj.ShowDialog = Windows.Forms.DialogResult.OK Then
                MsgBox(IO.Directory.GetParent(obj.FileName).FullName)
            End If
        End Using