首页 > 开发 > 综合 > 正文

用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
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表