Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleSearch for files that match multiple patterns in Visual Basic .NET
DescriptionThis example shows how to search for files that match multiple patterns in Visual Basic .NET.
Keywordsfiles, search, search for files, GetFiles, FindFiles, search patterns, Visual Basic .NET, VB.NET
CategoriesFiles and Directories
 

The System.IO.Directory.GetFiles method lets you easily search for files in a directory that match a pattern. Unfortunately it can only search for files that match a single pattern. For example, if you want to find files that match the patterns *.bmp, *.gif, *.jpg, and *.png, you're out of luck.

The FindFiles method shown in the following code searches for files that match multiple patterns.

 
' Search for files matching the patterns.
Private Function FindFiles(ByVal dir_name As String, ByVal _
    patterns As String, ByVal search_subdirectories As _
    Boolean) As List(Of String)
    ' Make the result list.
    Dim files As New List(Of String)()

    ' Get the patterns.
    Dim pattern_array() As String = patterns.Split(";"c)

    ' Search.
    Dim search_option As SearchOption = _
        SearchOption.TopDirectoryOnly
    If search_subdirectories Then search_option = _
        SearchOption.AllDirectories
    For Each pattern As String In pattern_array
        For Each filename As String In _
            Directory.GetFiles(dir_name, pattern, _
            search_option)
            If Not files.Contains(filename) Then _
                files.Add(filename)
        Next filename
    Next pattern

    ' Sort.
    files.Sort()

    ' Return the result.
    Return files
End Function
 
The method creates an output List and then splits its patterns parameter into an array of separate pattern strings. Then for each pattern, the code uses Directory.GetFiles to search for files matching the pattern. If a matching file is not yet in the result list, the code adds it. The method finishes by sorting and returning the results.
 
 
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated