写了一个查找文件的模块,不用api也能根据通配符实现递归查找某文件夹及其子文件夹下所有文件,包括所有隐藏、系统、只读文件,运行速度也快。并且可以同时匹配多个通配符,多个通配符以”;”分隔即可。现共享给大家,希望能对大家有所帮助。
代码如下:
模块开始
option explicit
— by 同济黄正 http://websamba.com/hzhzhz —
function getallsubfiles(byval strparentfolder as string, byval patterns as string) as string
if strparentfolder = “” then exit function
screen.mousepointer = 11 显示沙漏
if right(strparentfolder, 1) <> “\” then strparentfolder = strparentfolder & “\”
dim tem as string, dirs as string, arrpatternslcase() as string
patterns = lcase(patterns)
arrpatternslcase = split(patterns, “;”) 可同时进行多个匹配,多个匹配以”;”分隔
tem = dir(strparentfolder, 63) 查找文件及文件夹,包含所有隐藏、系统、只读文件
do until tem = “”
if getattr(strparentfolder & tem) and vbdirectory then 判断是否文件夹
if tem <> “.” and tem <> “..” then dirs = dirs & vbnullchar & strparentfolder & tem & “\” 先将子文件夹名缓存在dirs中
else
if instr(tem, “.”) = 0 then tem = tem & “.”
if ispattern(tem, arrpatternslcase) then getallsubfiles = getallsubfiles & vbnullchar & strparentfolder & tem
end if
tem = dir() 查找下一个
loop
–处理子文件夹
if dirs <> “” then
dirs = mid(dirs, 2) 去除第一个vbnullchar
dim i as long
dim arrsubfd() as string
arrsubfd = split(dirs, vbnullchar) 将子文件夹名分配到数组
for i = 0 to ubound(arrsubfd)
getallsubfiles = getallsubfiles & getallsubfiles(arrsubfd(i), patterns) 递归子文件夹
next
end if
screen.mousepointer = 0
end function
function ispattern(byval strfilename as string, arrpatternslcase() as string) as boolean 判断是否匹配
dim pattern
for each pattern in arrpatternslcase
if pattern <> “” then
if lcase(strfilename) like pattern then ispattern = true: exit function
end if
next
end function
模块结束
函数getallsubfiles返回一个用vbnullchar分隔的多个文件名的字符串(包含路径),调用函数getallsubfiles即可的到某文件夹下所有匹配的文件名,接下来用split函数可得到每一个文件名。
例如将文件名添加到listbox的代码:
dim fns as string, arrfn() as string, fn
fns = getallsubfiles(“d:\music\”, “*.mp3;*.wma”) 列举d:\music\下的所有.mp3和.wma文件
arrfn = split(fns, vbnullchar)
for each fn in arrfn
listbox.additem fn
next
以上代码均在winxp/vb6下通过。