Recursive File Search in VB.NET

Viewed 6994

I have a function that does a recursive directory search for files but when I search a Drive I get Access denied errors which stops the search. How can I avoid these errors?

Here's the function I use:

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

Thanks for any solutions.

3 Answers

Thanks for the code, it worked, but after taking a closer look, i found this single line would do the job:

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

just changing the search option from TopDirectoryOnly to AllDirectories. I always look to use native functions.

Related