用VB函數Dir實現遞歸搜索目錄
2024-07-21 02:20:29
供稿:網友
注冊會員,創建你的web開發資料庫,
用vb函數dir實現遞歸搜索目錄
我在很久以前就實現了這個方法了.它沒有采用任何的控件形式.也沒有調用系統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