vb.net get filename list from wildcard

前端 未结 4 912
野趣味
野趣味 2021-01-27 13:48

I have string say \"c:\\debug\\ *.txt\" In Debug folder there are severeal .txt files , say test1.txt test2.txt test3.txt .

How can I get from this string c:\\debug\\ *.

4条回答
  •  不要未来只要你来
    2021-01-27 14:27

    This should do it for you. It'll handle wildcards in directory part and filename part

    Private Function GetFiles(ByVal Path As String) As List(Of String)
    
        Dim drivePart As String, dirPart As String, filePart As String
    
        drivePart = Path.Substring(0, Path.IndexOf("\") + 1)
        dirPart = Path.Substring(Path.IndexOf("\") + 1, Path.LastIndexOf("\") - Path.IndexOf("\") - 1)
        filePart = Path.Substring(Path.LastIndexOf("\") + 1)
    
    
        Dim directories As New List(Of String)
        Dim files As New List(Of String)
    
    
        '' Walk directory tree finding matches
        '' This should handle wildcards in any part of the path
        Dim currentIndex As Integer = 0
        Dim directoryMatch As String() = dirPart.Split("\")
        For Each directory As String In directoryMatch
            WalkDirectories(drivePart, directories, directoryMatch, currentIndex)
            currentIndex += 1
        Next
    
        For Each directory As String In directories
            files.AddRange(System.IO.Directory.GetFiles(directory, filePart))
        Next
    
    
        Return files
    
    End Function
    
    Private Sub WalkDirectories(ByVal dirPart As String, ByVal directories As List(Of String), ByVal directoryMatch As String(), ByVal currentIndex As Integer)
    
        If currentIndex = directoryMatch.Length Then Return
    
        For Each d As String In System.IO.Directory.GetDirectories(dirPart, directoryMatch(currentIndex))
            directories.Add(d)
    
    
            WalkDirectories(System.IO.Path.Combine(dirPart, d), directories, directoryMatch, currentIndex + 1)
        Next
    End Sub
    

    Edit: just noticed that it wont handle UNC paths but it should be pretty easy to modify for that if you need to Editted again to handle multiple directory levels and wildcards at multiple levels (eg C:\debug\12*\log1*\errors*.txt

提交回复
热议问题