Searching By File Extensions VB.NET [duplicate]

北城余情 提交于 2019-12-02 04:32:50

You didn't instantiate the Dim filelist() As String array. Try di.GetFiles(searchPattern)

Dim files() as FileInfo = di.GetFiles(searchPattern)

Use static method Directory.GetFiles that returns an array string

Dim files =  Directory.GetFiles(Path,searchPattern,searchOption)

Demo:

 Dim files() As String
 files = Directory.GetFiles(path, "*.exe", SearchOption.TopDirectoryOnly)
 For Each FileName As String In files
     Console.WriteLine(FileName)
 Next

Recursive directory traversal:

   Sub Main()
        Dim path = "c:\jam"
        Dim fileList As New List(Of String)

        GetAllAccessibleFiles(path, fileList)

        'Convert List<T> to string array if you want
        Dim files As String() = fileList.ToArray

        For Each s As String In fileList
            Console.WriteLine(s)
        Next
    End Sub

    Sub GetAllAccessibleFiles(path As String, filelist As List(Of String))
        For Each file As String In Directory.GetFiles(path, "*.*")
            filelist.Add(file)
        Next
        For Each dir As String In Directory.GetDirectories(path)
            Try
                GetAllAccessibleFiles(dir, filelist)
            Catch ex As Exception

            End Try
        Next
    End Sub

Use System.IO.Directory.EnumerateFiles method and pass SearchOption.AllDirectories in to traverse the tree using a specific search pattern. Here is an example:

foreach (var e in Directory.EnumerateFiles("C:\\windows", "*.dll", SearchOption.AllDirectories))
{
    Console.WriteLine(e);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!