当前位置:编程学习 > VB >>

用VB实现文件查找功能

答案:
用VB实现文件查找功能
在VB中要实现查找文件功能,我们可以利用VB的DIR函数进行递归来实现。每次使用DIR函数后,比较是否有要查找的文件,再检查是否有子目录,若有,利用递归继续查找,这样可对整个盘进行查找。
  下面是一个例子,查找DOS目录下的所有EXE文件,统计EXE文件的数目并列出文件名。本程序会查找当前路径下的所有文件和子目录,与WIN95的“包含子文件夹”的查找功能类似。
程序与注释如下:
1.在窗体中加一命令按钮Command1,Caption=查找示例,双击此按钮,写如下代码:
Private Sub Command1-Click()
Dim ff() As String′定义一个字符串数组用来保存找到的文件名称
Dim fn As Long′保存找到的文件数目
fn=TreeSearch(″C:%%dos″,″*.exe″,ff())
Print″找到文件数目为″;fn
For I=1 To fn
Print ff(I)
Next
End Sub
2.插入一模块Modulel.bas,写如下代码:
Option Explicit
Public Function TreeSearch(ByVal sPath As String,ByVal sFileSpec As String,sFiles() As String)
As Long
Static 1Files As Long′文件数目
Dim sDir   As String
Dim sSubDirs() As String′存放子目录名称
Dim 1Index As Long
If Right(sPath,1)<>″%%″Then sPath=sPath&″%%″
sDir=Dir(sPath & sFileSpec)
′获得当前目录下文件名和数目
Do While Len(sDir)
1Files=1Files+1
ReDim Preserve sFiles(1 To 1Files)
sFiles(1Files)=sPath&sDir
sDir=Dir
Loop
′获得当前目录下的子目录名称
1Index=0
sDir=Dir(sPath&″*.*″,16)
Do While Len(sDir)
If Left(sDir,1)<>″.″Then ′skip.and..
′找出子目录名
If GetAttr(sPath & sDir)And vbDirectory Then
1Index=lIndex +1
′保存子目录名
Redim Preserve sSubDirs(1 To 1Index)
sSubDirs(1Index)=sPath & sDir &″%%″
End If
End If
sDir=dir
Loop
For 1Index=1 To 1Index
′查找每一个子目录下文件,这里利用了递归
Call TreeSearch(sSubDirs(1Index),sFileSpec,sFiles())
Next 1Index
TreeSearch=1Files
End Function
3.保存文件,按F5运行,单击命令按钮即可。
程序运行环境:VB 4.0 (32位),中文WIN95。

上一个:利用form2控制form1的文本框
下一个:如何在Windows操作系统中改变文件打开方式

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,