通过Directory.GetFiles()循环安全系统文件而不抛出异常

时间:2012-09-19 23:21:34

标签: .net vb.net

  

可能重复:
  Ignore folders/files when Directory.GetFiles() is denied access

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

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

proplem将是异常[UnauthorizedAccessException],因为循环到达安全文件夹'System volume information',程序将停止。 我需要跳过此异常,并在除受保护文件和文件夹(如系统卷信息)之外的每个文件上进行代码循环。

很抱歉给您带来不便....

1 个答案:

答案 0 :(得分: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