.netvb.netexceptionunauthorizedaccessexcepti

How to skip Directory or file when UnauthorizedAccessException occurs


Code is below. I am trying to fetch files from a specific path as sDirPath and then store in a tree view, basically making a custom folder browser dialog box. But the issue is, when I get system files or folders which are inaccessible, I get UnauthorizedAccessException. It occurs on folders or files like hidden and system folders or files e.g $recyle.bin in C:\ or shortcut of Documents and Settings. I just want to skip these folders or files. I don't want to fetch them.

Dim sAllfiles() As String = Directory.GetFiles(sDirPath, "*.*")
For Each sfile As String In sAllfiles          
    Dim objFileInformation As FileInfo = New FileInfo(sfile)
    Dim tnTreeNodeSub As TreeNode
    tnTreeNodeSub=tnTreeNodeRootDirectory.Nodes.Add(objFileInformation.Name)
Next    

Solution

  • Try .. Catch statements are for exactly this.

    For example, this will only ignore an UnauthorizedAccessException. Any other exception will still kill the loop.

    Dim sAllfiles() As String = Directory.GetFiles(sDirPath, "*.*")
    For Each sfile As String In sAllfiles
        Try
            Dim objFileInformation As FileInfo = New FileInfo(sfile)
            Dim tnTreeNodeSub As TreeNode
            tnTreeNodeSub=tnTreeNodeRootDirectory.Nodes.Add(objFileInformation.Name)
        Catch ex As UnauthorizedAccessException
            Continue For 'Ignore the exception and move on
        End Try
    Next