Youssef13
Youssef13

Reputation: 4993

Searching for files ignoring access denied error

I'm trying to search for files in the PC.. and the problem is that some of the directories can't be accessed. What I want is to ignore such directories and continue searching. Try Catch doesn't do that.

Here is the way I was trying to search with:

Directory.GetFiles("C:\", "*.*", SearchOption.AllDirectories)

Is there a good way to search with ignoring of any error so the operation completes successfully ?

Upvotes: 1

Views: 56

Answers (1)

Kelly Barnard
Kelly Barnard

Reputation: 1141

Since you have directories that can't be accessed you will have to traverse the filesystem yourself here is a simple method that will do this.

Private Sub ProcessDirectory(sDirectory As String, fileList As List(Of String))

    Try
        Dim files As String() = System.IO.Directory.GetFiles(sDirectory)
        fileList.AddRange(files)
        Dim directories As String() = System.IO.Directory.GetDirectories(sDirectory)
        For Each direct As String In directories
            ProcessDirectory(direct, fileList)
        Next
    Catch ex As Exception

    End Try

End Sub

Usage

Dim fileList As List(Of String) = New List(Of String)()

ProcessDirectory("C:\", fileList)

depending on how many files are on your drive this could take some time. After ProcessDirectory is called the fileList Collection will contain all files from accessible directories.

Upvotes: 1

Related Questions