利用VB函數Dir()實現遞歸搜索目錄
發表于:2007-07-14來源:作者:點擊數:
標簽:
我在很久以前就實現了這個方法了。它沒有采用任何的控件形式,也沒有調用系統API函數FindFirst,FindNext進行遞歸調用,和別人有點不同的就是我用的是 VB 中的Dir()函數。事實上,直接采用Dir()函數是不能進行自身的遞歸的調用的,但我們可以采用一種辦法把Di
我在很久以前就實現了這個方法了。它沒有采用任何的控件形式,也沒有調用系統API函數FindFirst,FindNext進行遞歸調用,和別人有點不同的就是我用的是
VB中的Dir()函數。事實上,直接采用Dir()函數是不能進行自身的遞歸的調用的,但我們可以采用一種辦法把Dir將當前搜索目錄的子目錄給保存下來,然后在自身的search(strPathName)遞歸函數中依次進行遞歸的調用,這樣就可以把指定的目錄搜索完畢。
具體代碼如下:
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'函數GetExtName
'功能:得到文件后綴名(擴展名)
'輸入:文件名
'輸出:文件后綴名(擴展名)
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Public Function GetExtName(strFileName As String) As String
Dim strTmp As String
Dim strByte As String
Dim i As Long
For i = Len(strFileName) To 1 Step -1
strByte = Mid(strFileName, i, 1)
If strByte <> "." Then
strTmp = strByte + strTmp
Else
Exit For
End If
Next i
GetExtName = strTmp
End Function
Public Function search(ByVal strPath As String, Optional strSearch As String = "") As Boolean
Dim strFileDir() As String
Dim strFile As String
Dim i As Long
Dim lDirCount As Long
On Error GoTo MyErr
If Right(strPath, 1) <> "\" Then strPath = strPath + "\"
strFile = Dir(strPath,
vbDirectory Or vbHidden Or vbNormal Or vbReadOnly)
While strFile <> "" '搜索當前目錄
DoEvents
If (GetAttr(strPath + strFile) And vbDirectory) = vbDirectory Then '如果找到的是目錄
If strFile <> "." And strFile <> ".." Then '排除掉父目錄(..)和當前目錄(.)
lDirCount = lDirCount + 1 '將目錄數增1
ReDim Preserve strFileDir(lDirCount) As String
strFileDir(lDirCount - 1) = strFile '用動態數組保存當前目錄名
End If
Else
If strSearch = "" Then
Form1.List1.AddItem strPath + strFile
ElseIf LCase(GetExtName(strPath + strFile)) = LCase(GetExtName(strSearch)) Then
'滿足搜索條件,則處理該文件
Form1.List1.AddItem strPath + strFile '將文件全名保存至列表框List1中
End If
End If
strFile = Dir
Wend
For i = 0 To lDirCount - 1
Form1.Label3.Caption = strPath + strFileDir(i)
Call search(strPath + strFileDir(i), strSearch) '遞歸搜索子目錄
Next
ReDim strFileDir(0) '將動態數組清空
search = True '搜索成功
Exit Function
MyErr:
search = False '搜索失敗
End Function
原文轉自:http://www.anti-gravitydesign.com