使用文件名过滤器查找文件

时间:2012-11-25 23:27:37

标签: vb.net list search visual-studio-2012 filtering

我使用的是VB.net VS2012,但在使用过滤器获取文件列表方面遇到了麻烦。

这是我的代码:

Public Function SearchAndAddToListWithFilter(ByVal path As String, ByVal Recursive As Boolean, arrayListOfFilters As ArrayList, ByRef listOfFiles As List(Of FileInfo))
    If Not Directory.Exists(path) Then Exit Function

    Dim initDirInfo As New DirectoryInfo(path)

    For Each oFileInfo In initDirInfo.GetFiles
        Application.DoEvents()
        For x = 0 To arrayListOfFilters.Count - 1
            If (oFileInfo.Name Like arrayListOfFilters(x)) Then
                listOfFiles.Add(oFileInfo)
            End If
        Next
    Next

    If Recursive Then
        For Each oDirInfo In initDirInfo.GetDirectories
            SearchAndAddToListWithFilter(oDirInfo.FullName, True, arrayListOfFilters, listOfFiles)
        Next
    End If

End Function

以下是如何使用它的示例:

    Dim stringFilterList As String = "*.mp3, *.docx, *.mp3, *.txt"
    Dim arrayListOfFilenameFilters As New ArrayList(stringFilterList.Split(","))
    Dim stringFolderPath As String = "C:\temp\folder\"
    Dim booleanSearchSubFolders As Boolean = True

    Dim listOfFilesFoundViaSearch As New List(Of FileInfo)
    SearchAndAddToListWithFilter(stringFolderPath, booleanSearchSubFolders, arrayListOfFilenameFilters, listOfFilesFoundViaSearch)

    For x = 0 To listOfFilesFoundViaSearch.Count - 1
        MsgBox(listOfFilesFoundViaSearch(x).FullName)
    Next

由于某种原因,代码只会将文件添加到满足过滤器列表中第一个条件的列表中。

我能帮助您使用此代码吗?

谢谢。

3 个答案:

答案 0 :(得分:1)

函数返回值,并且传递值ByRef不是这样做的方法。

以下功能可以使用:

Private Function SearchAndAddToListWithFilter(ByVal path As String, ByVal filters As String(), ByVal searchSubFolders As Boolean) As List(Of IO.FileInfo)
    If Not IO.Directory.Exists(path) Then
        Throw New Exception("Path not found")
    End If

    Dim searchOptions As IO.SearchOption
    If searchSubFolders Then
        searchOptions = IO.SearchOption.AllDirectories
    Else
        searchOptions = IO.SearchOption.TopDirectoryOnly
    End If

    Return filters.SelectMany(Function(filter) New IO.DirectoryInfo(path).GetFiles(filter, searchOptions)).ToList
End Function

并使用此功能:

Dim filters As String() = {"*.mp3", "*.docx", "*.bmp", "*.txt"}
Dim path As String = "C:\temp\folder\"

Dim foundFiles As List(Of IO.FileInfo) = SearchAndAddToListWithFilter(path, filters, True)

答案 1 :(得分:1)

@Steve提供的解决方案确实显示了.NET执行任务的方式。 但是我使用了递归解决方案,可能定义了最大深度和/或持续时间。为了完成本主题,我想发布代码:

''' <summary>
''' Search files in directory and subdirectories 
''' </summary>
''' <param name="searchDir">Start Directory</param>
''' <param name="searchPattern">Search Pattern</param>
''' <param name="maxDepth">maximum depth; 0 for unlimited depth</param>
''' <param name="maxDurationMS">maximum duration; 0 for unlimited duration</param>
''' <returns>a list of filenames including the path</returns>
''' <remarks>
''' recursive use of   Sub dirS
''' 
''' wallner-novak@bemessung.at
''' </remarks>
Public Shared Function dirRecursively(searchDir As String, searchPattern As String, _
                                    Optional maxDepth As Integer = 0, _
                                    Optional maxDurationMS As Long = 0) As List(Of String)
    Dim fileList As New List(Of String)
    Dim depth As Integer = 0
    Dim sw As New Stopwatch

    dirS(searchDir, searchPattern, maxDepth, maxDurationMS, fileList, depth, sw)

    Return fileList

End Function

''' <summary>
''' Recursive file search
''' </summary>
''' <param name="searchDir">Start Directory</param>
''' <param name="searchPattern">Search Pattern</param>
''' <param name="maxDepth">maximum depth; 0 for unlimited depth</param>
''' <param name="maxDurationMS">maximum duration; 0 for unlimited duration</param>
''' <param name="fileList">Filelist to append to</param>
''' <param name="depth">current depth</param>
''' <param name="sw">stopwatch</param>
''' <param name="quit">boolean value to quit early (at given depth or duration)</param>
''' <remarks>
''' wallner-novak@bemessung.at
''' </remarks>
Private Shared Sub dirS(searchDir As String, searchPattern As String, _
                            Optional maxDepth As Integer = 0, _
                            Optional maxDurationMS As Long = 0, _
                            Optional ByRef fileList As List(Of String) = Nothing, _
                            Optional ByRef depth As Integer = 0, _
                            Optional ByRef sw As Stopwatch = Nothing, _
                            Optional ByRef quit As Boolean = False)

    If maxDurationMS > 0 Then
        If depth = 0 Then
            sw = New Stopwatch
            sw.Start()
        Else
            If sw.ElapsedMilliseconds > maxDurationMS Then
                quit = True
                Exit Sub
            End If
        End If
    End If

    If maxDepth > 0 Then
        If depth > maxDepth Then
            quit = True
            Exit Sub
        End If
    End If

    ' check if directory exists
    If Not Directory.Exists(searchDir) Then
        Exit Sub
    End If

    ' find files
    For Each myFile As String In Directory.GetFiles(searchDir, searchPattern)
        fileList.Add(myFile)
    Next

    ' recursively scan subdirectories 
    For Each myDir In Directory.GetDirectories(searchDir)
        depth += 1
        dirS(myDir, searchPattern, maxDepth, maxDurationMS, fileList, depth, sw, quit)
        If quit Then Exit For
        depth -= 1
    Next

End Sub

答案 2 :(得分:0)

ListView1.Items.Clear()

        For Each files As String In System.IO.Directory.GetFiles(cmb_Drives.SelectedItem.ToString, txtSearch.Text)

            Dim ico As Icon = System.Drawing.Icon.ExtractAssociatedIcon(files)
            ImageList1.Images.Add(ico)

            Dim list As ListViewItem = New ListViewItem(My.Computer.FileSystem.GetFileInfo(files).FullName, ImageList1.Images.Count - 1)
            ListView1.Items.Add(list)

        Next