|
|
Title | List the files in a directory's subtree that match a pattern in VB .NET |
Description | This example shows how to list the files in a directory's subtree that match a pattern in VB .NET. |
Keywords | directory, subdirectory, list, files, list files, pattern, search, file search |
Categories | Files and Directories, VB.NET |
|
|
When you click the List button, the program reads a search pattern (e.g. *.txt) from a combo box. It makes a new DirectoryInfo object, passing its constructor the path to the directory to search, and passes the object and the search pattern to the ListFiles subroutine.
ListFiles calls the DirectoryInfo object's GetFiles method, passing it the search pattern, to find files in the directory that match the pattern. It loops through the files, adding their full names including path to a list box.
ListFiles then calls the DirectoryInfo object's GetDirectories method to list the directory's subdirectories. It loops through the subdirectories and recursively calls subroutine ListFiles for each.
|
|
Private Sub btnList_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnList.Click
' Get the pattern without stuff in parens.
Dim pattern As String = cboPattern.Text
If pattern.IndexOf("(") >= 0 Then
pattern = pattern.Substring(0, pattern.IndexOf("("))
End If
lstFiles.Items.Clear()
Dim dir_info As New DirectoryInfo(txtDir.Text)
ListFiles(lstFiles, pattern, dir_info)
End Sub
' Add the files in this directory's subtree to the ListBox.
Private Sub ListFiles(ByVal lst As ListBox, ByVal pattern _
As String, ByVal dir_info As DirectoryInfo)
' Get the files in this directory.
Dim fs_infos() As FileInfo = dir_info.GetFiles(pattern)
For Each fs_info As FileInfo In fs_infos
lstFiles.Items.Add(fs_info.FullName)
Next fs_info
fs_infos = Nothing
' Search subdirectories.
Dim subdirs() As DirectoryInfo = _
dir_info.GetDirectories()
For Each subdir As DirectoryInfo In subdirs
ListFiles(lst, pattern, subdir)
Next subdir
End Sub
|
|
|
|
|
|