0

Possible Duplicate:
Ignore folders/files when Directory.GetFiles() is denied access

I have this example which loop on files in a specific folder.

Imports system.IO
Dim Files() as string = Directory.GetFiles("D:\example","*.*",SearchOption.AllDirectories)
For Each S As String in Files
Listbox1.Items.Add(S)
Next

Till that point everything is alright. BUT THE PROBLEM GOES HERE: If the user select a top folder (Like a drive "D:\") The code will be as following:

Imports system.IO
    Dim Files() as string = Directory.GetFiles("D:\","*.*",SearchOption.AllDirectories)
    For Each S As String in Files
    Listbox1.Items.Add(S)
    Next

The proplem will be an exception [UnauthorizedAccessException] because the loop reached the secured folder 'System volume information', and the program will stop. I need to skip this exception and make the code loop on every file except the protected files and folders like System volume information.

Sorry for inconvenience....

Community
  • 1
  • 1

1 Answers1

0
Imports System.IO

Public Class Form1

  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim strFileList(-1) As String
    Call GetAllFiles("C:\", "*.*", strFileList)

    ListBox1.ClearSelected()
    For Each s As String In strFileList
      ListBox1.Items.Add(s)
    Next s
  End Sub

  Public Sub GetAllFiles(folder As String, searchPattern As String, ByRef fileList() As String)
    'First add all files in the current folder
    Dim strFiles(-1) As String
    Try
      strFiles = Directory.GetFiles(folder, searchPattern, SearchOption.TopDirectoryOnly)
    Catch ex As Exception
    End Try
    If strFiles.GetUpperBound(0) >= 0 Then
      Dim intStartIndex As Integer = fileList.GetUpperBound(0) + 1
      ReDim Preserve fileList(fileList.GetUpperBound(0) + strFiles.GetUpperBound(0) + 1)
      For i As Integer = 0 To strFiles.GetUpperBound(0)
        fileList(intStartIndex + i) = strFiles(i)
      Next i
    End If
    'Next go through all folders
    Dim strFolders(-1) As String
    Try
      strFolders = Directory.GetDirectories(folder, "*.*", SearchOption.TopDirectoryOnly)
    Catch ex As Exception
    End Try
    If strFolders.GetUpperBound(0) >= 0 Then
      For Each strFolder As String In strFolders
        Call GetAllFiles(strFolder, searchPattern, fileList)
      Next strFolder
    End If
  End Sub

End Class
SSS
  • 4,807
  • 1
  • 23
  • 44