在VB6中,删除目录及其内部所有文件和子目录是一个常见的需求。VB6本身没有直接提供这样的函数,但可以通过调用Windows API函数来实现。下面是一个示例函数DelFolder2
,用于递归删除指定目录及其所有内容。
DelFolder2 函数实现
vb
Option Explicit
Private Declare Function RemoveDirectory Lib "kernel32" Alias "RemoveDirectoryA" (ByVal lpPathName As String) As Long Private Declare Function DeleteFile Lib "kernel32" Alias "DeleteFileA" (ByVal lpFileName As String) As Long Private Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" (ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Long Private Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileA" (ByVal hFindFile As Long, lpFindFileData As WIN32_FIND_DATA) As Long Private Declare Function FindClose Lib "kernel32" (ByVal hFindFile As Long) As Long
Private 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 cAlternateFileName As String * 14 End Type
Private Type FILETIME dwLowDateTime As Long dwHighDateTime As Long End Type
Private Const MAX_PATH = 260
Public Function DelFolder2(ByVal sPath As String) As Boolean Dim hFind As Long Dim FindData As WIN32_FIND_DATA Dim sFile As String Dim sSubPath As String
' 确保路径以反斜杠结尾 If Right(sPath, 1) <> "\" Then sPath = sPath & "\"
' 查找目录中的第一个文件 sFile = sPath & "*.*" hFind = FindFirstFile(sFile, FindData)
If hFind = -1 Then DelFolder2 = False Exit Function End If
Do ' 跳过当前目录和上级目录 If FindData.cFileName = "." Or FindData.cFileName = ".." Then GoTo ContinueLoop End If
' 如果是子目录,递归删除 If (FindData.dwFileAttributes And vbDirectory) = vbDirectory Then sSubPath = sPath & FindData.cFileName If Not DelFolder2(sSubPath) Then FindClose hFind DelFolder2 = False Exit Function End If Else ' 删除文件 If Not DeleteFile(sPath & FindData.cFileName) Then FindClose hFind DelFolder2 = False Exit Function End If End If
ContinueLoop: Loop While FindNextFile(hFind, FindData) <> 0
' 关闭查找句柄 FindClose hFind
' 删除空目录 If Not RemoveDirectory(sPath) Then DelFolder2 = False Exit Function End If
DelFolder2 = True End Function
使用说明
函数参数:
DelFolder2
函数接收一个字符串参数sPath
,表示要删除的目录路径。返回值:函数返回一个布尔值,
True
表示删除成功,False
表示删除失败。注意事项:
使用此函数需要管理员权限,特别是在删除受保护的系统目录时。
删除操作是不可逆的,请确保目录中不再需要任何文件和子目录。
在生产环境中使用时,建议先备份重要数据。
示例调用
vb
Private Sub Command1_Click() Dim sFolderPath As String sFolderPath = "C:\Temp\ExampleFolder"
If DelFolder2(sFolderPath) Then MsgBox "目录删除成功。" Else MsgBox "目录删除失败。" End If End Sub
通过上述代码,可以实现递归删除指定目录及其所有内容的功能。