0

可能重复:
当 Directory.GetFiles() 被拒绝访问时忽略文件夹/文件

我有这个例子,它循环特定文件夹中的文件。

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

到那时一切都好。但问题出在这里:如果用户选择一个顶级文件夹(如驱动器“D:\”),代码将如下:

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

该问题将是一个异常[UnauthorizedAccessException],因为循环到达了安全文件夹“系统卷信息”,程序将停止。我需要跳过此异常并在每个文件上进行代码循环,除了受保护的文件和文件夹(如系统卷信息)。

对造成的不便表示歉意....

4

1 回答 1

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
于 2012-09-20T02:34:09.003 回答