在目录VB中搜索特定的扩展名 [英] Search specific extensions in a directory VB
问题描述
我试图在"C:\ test"和子目录中找到所有的.txt文件.
I am trying to find all .txt files within "C:\test" and sub directories.
目前,我已经设法使其在文档顶层内搜索.txt文件.
At the moment I have managed to make it search for .txt files within the top layer of my documents.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Dim path As String = "C:\\"
Dim txt As String = "*.txt"
For Each foundFile As String In My.Computer.FileSystem.GetFiles(
My.Computer.FileSystem.SpecialDirectories.MyDocuments,
FileIO.SearchOption.SearchAllSubDirectories, txt)
ListBox1.Items.Add(foundFile)
Next
End Sub
End Class
我想要类似的东西:
My.Computer.FileSystem.path,
FileIO.SearchOption.SearchAllSubDirectories, txt)
由于某些未知原因,无法搜索所有子目录.
The search all sub directories doesn't work for some unknown reason.
推荐答案
The Directory class (from System.IO namespace) has the method required and you don't need the For Each loop
Dim path As String = "C:\test"
Dim txt As String = "*.txt"
ListBox1.Items.AddRange(Directory.EnumerateFiles(path, txt, SearchOption.AllDirectories ).ToArray())
请记住,任何尝试读取诸如C:\System Volume Information
之类的保留文件系统文件夹的操作都会导致UnauthorizedAccessException,因此,如果您的路径变量是动态的,则准备好最终捕获此调用引发的任何异常
Keep in mind that any tentative to read reserved file system folders like C:\System Volume Information
will result in a UnauthorizedAccessException so, if your path variable is dynamic, then be prepared to catch eventually any exception raised by this call
编辑
这是VB.NET中 Mr Gravell 显示的过程的转换. https://stackoverflow.com/a/172575/1197518>这个问题,他在其中解释了一种从系统驱动器根目录遍历所有目录而不停止某些系统文件夹引发的异常的方法. System Volume Information
或Program
)
This is the conversion in VB.NET of the procedure shown by Mr Gravell in this question where he explains a method to traverse all the directories from the root of the system drive without stopping at the exceptions thrown by certain system folders (like System Volume Information
or Program
)
Delegate Sub ProcessFileDelegate(ByVal path As String)
Sub Main
Dim path = "c:\"
Dim ext = "*.txt"
Dim runProcess As ProcessFileDelegate = AddressOf ProcessFile
ApplyAllFiles(path, ext, runProcess)
End Sub
Sub ProcessFile(ByVal path As String)
' This is the sub where you process the filename passed in'
' you add it to your listbox or to some kind of collection '
ListBox1.Items.Add(path)
End Sub
' This is the recursive procedure that traverse all the directory and'
' pass each filename to the delegate that adds the file to the listbox'
Sub ApplyAllFiles(ByVal folder As String, ByVal extension As String, ByVal fileAction As ProcessFileDelegate)
For Each file In Directory.GetFiles(folder, extension)
fileAction.Invoke(file)
Next
For Each subDir In Directory.GetDirectories(folder)
Try
ApplyAllFiles(subDir, extension, fileAction)
Catch ex As Exception
' Console.WriteLine(ex.Message)'
' Or simply do nothing '
End Try
Next
End Sub
这篇关于在目录VB中搜索特定的扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!