How to handle Unauthorized Access Exception when getting files
I am trying to get a list of files using this line of code:
Code:
Dim files() As String = IO.Directory.GetFiles("D:\", "*.*", SearchOption.AllDirectories)
But it errors out on folders that are inaccessible, like the RecycleBin folder & the program stops. So how do I get a list of files in all folders, while skipping the inaccessible ones?
Re: How to handle Unauthorized Access Exception when getting files
An approach.
Code:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim startPath As New IO.DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments))
Dim startList As New List(Of IO.DirectoryInfo)
startList.AddRange(startPath.GetDirectories())
Dim allDirs As New List(Of IO.DirectoryInfo)
allDirs.AddRange(GetDirs(startList))
Dim listOfiles As New List(Of String)
For Each d As IO.DirectoryInfo In allDirs
Try
listOfiles.AddRange(IO.Directory.GetFiles(d.FullName, "*.*"))
Catch SecEx As UnauthorizedAccessException
'here is the sceurity exception
Debug.WriteLine(d.FullName)
End Try
Next
End Sub
Private Function GetDirs(ByVal theDirs As List(Of IO.DirectoryInfo)) As List(Of IO.DirectoryInfo)
'add directories. called recursively.
Dim rv As New List(Of IO.DirectoryInfo)
For Each d As IO.DirectoryInfo In theDirs
rv.Add(d)
Dim foo As List(Of IO.DirectoryInfo) = GetDirs(Me.GetSubDirs(d))
If Not (foo Is Nothing OrElse foo.Count = 0) Then
rv.AddRange(foo)
End If
Next
Return rv
End Function
Private Function GetSubDirs(ByVal theDir As IO.DirectoryInfo) As List(Of IO.DirectoryInfo)
Dim theSubDirs As New List(Of IO.DirectoryInfo)
Try
theSubDirs.AddRange(theDir.GetDirectories.ToList)
Catch SecEx As UnauthorizedAccessException
'here is the sceurity exception
'Debug.WriteLine(theDir.FullName)
End Try
Return theSubDirs
End Function
End Class
Re: How to handle Unauthorized Access Exception when getting files
[QUOTE=dbasnett;3944420]An approach.
Thanks. It works