我正在使用以下代码来获取目录信息。如果我搜索topleveldirectory它会很好。 但是当我搜索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 :(得分: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