2010-09-03 102 views
1

我正在使用以下代码来获取目录信息。它可以很好地工作,如果我搜索到很多目录。 但是,当我搜索alldirectories,它达到系统级别的信息并抛出错误。 有没有什么办法可以避免搜索系统级别的信息文件夹? 谢谢避免系统卷信息文件夹

Imports System.IO 
Public Class Form1 

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
     Dim di As New DirectoryInfo("d:\"), i As Integer 
     Dim aryFiles() As FileInfo = di.GetFiles("*.doc", SearchOption.TopDirectoryOnly) 
     For i = LBound(aryFiles) To UBound(aryFiles) 
      MsgBox(aryFiles(i).FullName) 
     Next i 
    End Sub 
End Class 

回答

0

此代码应该为你做的伎俩。

Imports System.IO 

Module Module1 

    Sub Main() 
     Dim folders = New DirectoryInfo("D:\").GetDirectories 
     Dim files = New List(Of FileInfo) 

     For Each folder In From d In folders Where d.Name <> "System Volume Information" 
      files.AddRange(folder.GetFiles("*.doc", SearchOption.TopDirectoryOnly)) 
     Next 

     For Each File In files 
      MsgBox(File.FullName) 
     Next 
    End Sub 

End Module 

我假设你的项目是.NET 3.5或更高版本。如果假设错误,通知我。


编辑
既然你要求它,我砍死在一起,代码自动跳过无法访问的文件夹。我没有广泛地测试代码,所以我不能保证它是没有错误的。

Imports System.IO 

Module Module1 

    Sub Main() 
     Dim folders = GetAllSubFolders("D:\Alex\Music") 
     Dim files = New List(Of FileInfo) 

     For Each folder In folders 
      files.AddRange(folder.GetFiles("*.doc", SearchOption.TopDirectoryOnly)) 
     Next 

     For Each File In files 
      Console.WriteLine(File.FullName) 
     Next 

     Console.ReadLine() 
    End Sub 

    Function GetAllSubFolders(ByVal path As String) As IEnumerable(Of DirectoryInfo) 
     Dim subFolders As New List(Of DirectoryInfo) 

     Try 
      subFolders.AddRange(New DirectoryInfo(path).GetDirectories()) 
     Catch ex As Exception 
      'error handling code goes here' 
     End Try 

     Dim innerSubFolders As New List(Of DirectoryInfo) 
     For Each folder In subFolders 
      innerSubFolders.AddRange(GetAllSubFolders(folder.FullName)) 
     Next 

     'add the inner sub folders' 
     subFolders.AddRange(innerSubFolders) 

     'return the directories' 
     Return subFolders 
    End Function 

End Module 
+0

您的代码有效!谢谢,但有很多文件夹被拒绝访问。这是不可能命名每个人和每个人的。 我需要找到其他方法。 谢谢任何​​方式 – 2010-09-03 14:58:01

0

不幸的不是。你必须通过做自己的递归来解决这个问题,你可以添加自己的异常处理程序来忽略这些错误。