views:

71

answers:

1

I am trying to search the C:\ drive for all files with a certain extension. I am using the following code which is working fine, however when it encounters an error the whole process stops rather than continuing with the scan. (running in backgroundworker, hence the invoke)

Private Sub ScanFiles(ByVal rootFolder As String, ByVal fileExtension As String)

        'Determine if the current folder contains any sub folders
        Dim subFolders() As String = System.IO.Directory.GetDirectories(rootFolder)

        For Each subFolder As String In subFolders
            ScanFiles(subFolder, fileExtension)
        Next
            For Each file As String In System.IO.Directory.GetFiles(rootFolder, fileExtension)
                lb.BeginInvoke(New AddValue(AddressOf AddItems), file)
            Next

    End Sub

How can I make this code continue once an error is encountered? Thanks for your help.

A: 

If you don't have access to explore C drive itself then you are out of luck. but if you are getting an exception because you don't have access to some child folder in the tree, you can avoid it by putting your code in an try-catch block.

Private Sub ScanFiles(ByVal rootFolder As String, ByVal fileExtension As String)
   'Determine if the current folder contains any sub folders    '
   try

        Dim subFolders() As String = System.IO.Directory.GetDirectories(rootFolder)

        For Each subFolder As String In subFolders
            ScanFiles(subFolder, fileExtension)
        Next
            For Each file As String In System.IO.Directory.GetFiles(rootFolder, fileExtension)
                lb.BeginInvoke(New AddValue(AddressOf AddItems), file)
            Next
    catch (Ex As UnauthorizedAccessException)
       'Ignore Access Errors   '
    end try
End Sub
NimsDotNet
Wow... I'm embarrassed at how simple it was lol. Does the catch have to be Unauth.AccessException specific, or can I just use the generic 'Catch ex As Exception'?
Shane
Yes Catch ex As Exception will work.
Tim Murphy
@Shane - you should avoid catching the base `Exception` if at all possible. Catch only those exceptions that can be raised. If a really unexpected exception is raised you want to know about it and your code as is might not be able to cope.
ChrisF