Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleLet the user browse for a folder in Visual Basic .NET
DescriptionThis example shows how to let the user browse for a folder in Visual Basic .NET.
Keywordsbrowse, browse for folder, SHBrowseForFolder, API, VB.NET
CategoriesVB.NET, Files and Directories, API
 
The BrowseForFolder function uses the SHBrowseForFolder API function to let the user browse for a folder. It returns the folder's path or Nothing if the user cancels.
 
Module BrowseForFolderCode
    Private Structure BrowseInfo
        Public hWndOwner As IntPtr
        Public pidlRoot As Integer
        Public sDisplayName As String
        Public sTitle As String
        Public ulFlags As Integer
        Public lpfn As Integer
        Public lParam As Integer
        Public iImage As Integer
    End Structure

    ' Code omitted...

    ' Let the user browse for a folder.
    ' Return the folder or Nothing if the user cancels.
    Public Function BrowseForFolder(ByRef dialog_title As _
        String, ByRef frm As Form) As String
        Try
            Dim browse_info As BrowseInfo
            With browse_info
                .hWndOwner = frm.Handle
                .pidlRoot = 0
                .sDisplayName = Space$(260)
                .sTitle = dialog_title
                .ulFlags = BIF_RETURNONLYFSDIRS
                .lpfn = 0
                .lParam = 0
                .iImage = 0
            End With

            Dim item As Integer = _
                SHBrowseForFolder(browse_info)

            Dim path As String = New String(" "c, MAX_PATH)
            If SHGetPathFromIDList(item, path) = 0 Then
                path = Nothing
            Else
                path = path.Trim
            End If

            CoTaskMemFree(item)
            Return path
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            Return Nothing
        End Try
    End Function
End Module
 
The following code shows how a program can use this function.
 
Private Sub btnBrowseForFolder_Click(ByVal sender As _
    System.Object, ByVal e As System.EventArgs) Handles _
    btnBrowseForFolder.Click
    Dim new_folder As String = BrowseForFolder("Select " & _
        "Folder", Me)
    If Not (new_folder Is Nothing) Then txtFolder.Text = _
        new_folder
End Sub
 
 
Copyright © 1997-2006 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated