避免系统卷信息文件夹 [英] Avoid system Volume information folder
问题描述
我正在使用以下代码来获取目录信息.如果我搜索 topleveldirectory 效果很好.但是当我搜索所有目录时,它会到达系统级信息并引发错误.有没有办法避免搜索系统级信息文件夹?谢谢
I am using following code to get directory info. it works well if I search topleveldirectory. But when i search alldirectories, it reaches system level information and throws error. Is there any way to avoid searching system level information folder? Thanks
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
推荐答案
这段代码应该可以解决问题.
This code should do the trick for you.
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 或更高版本.如果假设错误,请通知我.
I'm assuming your project is .NET 3.5 or higher. Notify me if the assumption is wrong.
编辑
既然你要求它,我把代码组合起来自动跳过无法访问的文件夹.我没有对代码进行广泛的测试,所以我不能保证它不会有错误.
Edit
Since you requested for it, I hacked together code to automatically skip inaccessible folders. I did not test the code extensively so I cannot guarantee it will be bug-free.
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
这篇关于避免系统卷信息文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!