当前位置:文档之家› VB6遍历文件夹

VB6遍历文件夹

//思路: 使用FINDFIRST FINDNEXT 函数递归实现查找
/*
在VB中WIN32_FIND_DATA 的
cFileName 返回的总是256个字符即MAX_PATH长度的字符,其中包含文件名和空格,需用getstr 获取取中的文件名
*/
’程序:
'引用 microsft scripting runtime
Dim file As New FileSystemObject
Dim txtstream As TextStream
Public Sub cbfindfile(str2 As String)
fext = getext(str2)
If (LCase(fext) = "cpp" Or LCase(fext) = "h" Or LCase(fext) = "inc" Or LCase(fext) = "txt" Or LCase(fext) = "doc") Then
Set txtstream = file.OpenTextFile(str2, ForReading)
strtxt = LCase(txtstream.ReadAll)
pos = InStr(1, strtxt, "p0", 1) '查找的内容
If (pos <> 0) Then
Form1.List1.AddItem str2
End If
End If
End Sub
Private Sub Command1_Click()
findfile "d:\51"
End Sub
’模块文件:
Public Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" (ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Long
'查找下一个文件的API
Public Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileA" (ByVal hFindFile As Long, lpFindFileData As WIN32_FIND_DATA) As Long
'获取文件属性的API
Public Declare Function GetFileAttributes Lib "kernel32" Alias "GetFileAttributesA" (ByVal lpFileName As String) As Long
'关闭查找文件的API
Public Declare Function FindClose Lib "kernel32" (ByVal hFindFile As Long) As Long Const MAX_PATH = 260
Const MAXDWORD = &HFFFF
Const FILE_ATTRIBUTE_DIRECTORY = &H10
Public Type FILETIME
dwLowDateTime As Long
dwHighDateTime As Long
End Type
Dim tempstr As String
'定义类(用于查找文件)
Public Type WIN32_FIND_DATA
dwFileAttributes As Long
ftCreationTime As FILETIME
ftLastAccessTime As FILETIME
ftLastWriteTime As FILETIME
nFileSizeHigh As Long
nFileSizeLow As Long
dwReserved0 As Long
dwReserved1 As Long
cFileName As String * MAX_PATH
cAlternate As String * 14
End Type
Public Function getstr(str1 As String) As String Dim slen As Long
For i = 1 To MAX_PATH
If (Asc(Mid(str1, i, 1)) = 0) Then
slen = i - 1
Exit For
End If
Next
getstr = Left(str1, slen)
End Function
Public Sub findfile(path As String) '遍历文件
Dim fhand As Long
Dim wfd As WIN32_FIND_DATA
Dim bl As Boolean
bl = True
fhand = FindFirstFile(path & "\*.*", wfd)
While bl
fname = getstr(wfd.cFileName)
If (fname <> "." And fname <> "..") Then
If (wfd.dwFileAttributes And vbDirectory) Then findfile (path & "\" & fname)
Else
Form1.cbfindfile (path & "\" & fname) '找到文件
End If
End If
bl = FindNextFile(fhand, wfd)
Wend
FindClose (fhand)
End Sub
Public Function getext(str1 As String) As String '获取扩展名For i = Len(str1) To 1 Step -1
If (Mid(str1, i, 1) = ".") Then
getext = Right(str1, Len(str1) - i)
Exit For
End If
Next
End Function。

相关主题