如何在VB中使用Directory.GetFiles?

时间:2012-09-03 17:47:17

标签: vb.net

我基本上遵循MS示例。以下是示例。

Imports System
Imports System.IO

Public Class Test
Public Shared Sub Main()
    Try 
        ' Only get files that begin with the letter "c." 
        Dim dirs As String() = Directory.GetFiles("c:\", "c*")
        Console.WriteLine("The number of files starting with c is {0}.", dirs.Length)
        Dim dir As String 
        For Each dir In dirs
            Console.WriteLine(dir)
        Next 
    Catch e As Exception
        Console.WriteLine("The process failed: {0}", e.ToString())
    End Try 
End Sub 
End Class

我稍微修改一下,以便我可以将它用作文件搜索功能。但是,在" For F in Directory.GetFiles(d,FileName)"中存在错误。我做错了什么?

    Public Sub DirSearch(ByVal sDir As String, ByVal FileName As String)
    Dim d As String
    Dim f As String

    Try
        For Each d In Directory.GetDirectories(sDir)
            For Each f In Directory.GetFiles(d, FileName)
                If f = FileName Then
                    Form1.TextBox4.Text = "1"
                Else
                    Form1.TextBox4.Text = "0"
                End If
            Next
            DirSearch(d, FileName)
        Next
    Catch excpt As System.Exception
        Debug.WriteLine(excpt.Message)
    End Try
End Sub

1 个答案:

答案 0 :(得分:1)

我发现了这个,这解决了我的问题

Public Sub DirSearch(ByVal sDir As String, ByVal FileName As String)
    For Each foundFile As String In My.Computer.FileSystem.GetFiles(sDir, FileIO.SearchOption.SearchAllSubDirectories, FileName)
       "Do the work here"
    Next
End Sub