vb.net从通配符获取文件名列表 [英] vb.net get filename list from wildcard
问题描述
我有一个字符串说"c:\ debug \ * .txt" 在Debug文件夹中,有严重的.txt文件,例如test1.txt test2.txt test3.txt.
I have string say "c:\debug\ *.txt" In Debug folder there are severeal .txt files , say test1.txt test2.txt test3.txt .
如何从字符串c:\ debug \ * .txt中获取通配符文件数组?
How can I get from this string c:\debug\ *.txt an array of wildcard files?
a(0)=c:\debug\test1.txt
a(1)=c:\debug\test2.txt
a(2)=c:\debug\test3.txt
该字符串也可能类似于"C:\ logs \ 12 * \ * .log"
It is also possible that the string would be something like "C:\logs\12*\ *.log"
a(0)=C:\logs\120114\01.log
a(0)=C:\logs\120114\02.log
a(0)=C:\logs\120114\03.log
等
有人对此有任何想法吗?
Anyone have any ideas on this?
推荐答案
这应该为您完成.它将处理目录部分和文件名部分中的通配符
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
只是注意到它不会处理UNC路径,但是如果您需要修改它,应该很容易进行修改. 再次编辑以处理多个目录级别和多个级别的通配符(例如C:\ debug \ 12 * \ log1 * \ errors * .txt
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
这篇关于vb.net从通配符获取文件名列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!