VB.NET中的递归文件搜索

时间:2017-05-22 02:05:34

标签: vb.net recursion file-search

我有一个函数可以对文件进行递归目录搜索,但是当我搜索某个驱动器时,我会收到拒绝访问的错误,这会停止搜索。我该如何避免这些错误?

这是我使用的功能:

lstSearch = GetFilesRecursive(FolderBrowserDialogMain.SelectedPath)

Private Function GetFilesRecursive(ByVal path As String) As List(Of String)
    Dim lstResult As New List(Of String)
    Dim stkStack As New Stack(Of String)
    stkStack.Push(path)
    Do While (stkStack.Count > 0)
        Dim strDirectory As String = stkStack.Pop
        Try
            lstResult.AddRange(Directory.GetFiles(strDirectory, "*.mp3"))
            Dim strDirectoryName As String
            For Each strDirectoryName In Directory.GetDirectories(strDirectory)
                stkStack.Push(strDirectoryName)
            Next
        Catch ex As Exception
        End Try
    Loop
    Return lstResult
End Function

感谢任何解决方案。

3 个答案:

答案 0 :(得分:1)

感谢代码,它可以正常工作,但是仔细查看后,我发现这行代码可以完成工作:

myfiles = IO.Directory.GetFiles(strpath, "*.*", IO.SearchOption.AllDirectories)

只需将搜索选项从TopDirectoryOnly更改为AllDirectories。我一直希望使用本机功能。

答案 1 :(得分:0)

您可以通过递归循环遍历文件和目录并添加一些try catch逻辑来实现此目的。

Public Class MainClass

    Private Function GetAllFiles(ByVal strPath As String) As List(Of String)

        Dim lst As New List(Of String)

        GetFiles(strPath, lst)

        Return lst
    End Function


    Public Sub GetFiles(ByVal strpath As String, ByRef lstfiles As List(Of String))



        Try

            Dim str As String() = IO.Directory.GetFiles(strpath, "*.*", IO.SearchOption.TopDirectoryOnly)
            'Get Current Directory files
            lstfiles.AddRange(str)

            'Loop  over sub-directories
            For Each strDirectory As String In IO.Directory.GetDirectories(strpath, "*.*", IO.SearchOption.TopDirectoryOnly)


                Me.GetFiles(strDirectory, lstfiles)


            Next

        Catch ex As UnauthorizedAccessException
            'Access Denied exception

        Catch ex1 As Exception
            'Other exceptions

        End Try

    End Sub



End Class

答案 2 :(得分:0)

我唯一改变以避免访问被拒绝错误的是使用Try / Catch进行UnauthorizedAccessException,然后我就是没有处理它。当它完成搜索时,无论如何都要使用lstResult。我在BackgroundWorker中有这个代码,所以它不会弄乱UI。

    Dim lstResult As New List(Of String)
    Dim stkStack As New Stack(Of String)
    stkStack.Push(SearchSelectedPath)
    Do While (stkStack.Count > 0)
        Dim strDirectory As String = stkStack.Pop
        Try
            lstResult.AddRange(Directory.GetFiles(strDirectory, "*.mp3"))
            Dim strDirectoryName As String
            For Each strDirectoryName In Directory.GetDirectories(strDirectory)
                stkStack.Push(strDirectoryName)
            Next
        Catch ex As UnauthorizedAccessException

        End Try
    Loop

我在大约一分半钟内搜索了我的C / D驱动器,发现每个驱动器中有近150个MP3,没有错误。