在目录VB

时间:2016-01-21 12:23:52

标签: .net vb.net file

我正在尝试查找“C:\ test”和子目录中的所有.txt文件。

目前我已设法在文档的顶层搜索.txt文件。

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)

搜索所有子目录由于某种未知原因不起作用。

2 个答案:

答案 0 :(得分:2)

Directory class(来自System.IO名称空间)具有所需的方法,您不需要For Each循环

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,因此,如果您的路径变量是动态的,那么请准备好最终捕获此调用引发的任何异常

修改

这是VB.NET中Mr Gravellthis question中显示的过程的转换,他解释了一种从系统驱动器根目录遍历所有目录而不停止抛出异常的方法某些系统文件夹(例如System Volume InformationProgram

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

答案 1 :(得分:0)

你可以试试

Directory.GetFiles("searchpath", "extension")

而不是

My.Computer.FileSystem.GetFiles()