我想知道是否有人可以帮助我使用vb6函数来删除目录中的所有文件(不包括子目录)。
答案 0 :(得分:8)
一行,使用VB6语句Kill
Kill "c:\doomed_dir\*.*"
help topic says“在Microsoft Windows中,Kill支持使用多字符(*)和单字符(?)通配符来指定多个文件”。
顺便说一句 - 我更喜欢避免使用Microsoft Scripting Runtime(包括FileSystemObject)。根据我的经验,它偶尔会在用户计算机上崩溃,可能是因为他们的IT部门对病毒感到偏执。
答案 1 :(得分:4)
我相信这应该有效:
Dim oFs As New FileSystemObject
Dim oFolder As Folder
Dim oFile As File
If oFs.FolderExists(FolderSpec) Then
Set oFolder = oFs.GetFolder(FolderSpec)
'caution!
On Error Resume Next
For Each oFile In oFolder.Files
oFile.Delete True 'setting force to true will delete a read-only file
Next
DeleteAllFiles = oFolder.Files.Count = 0
End If
End Function
答案 2 :(得分:2)
我没有测试过每个场景,但它应该可行。它应该删除每个文件,如果文件被锁定或者你没有访问权限,你应该得到错误70,它会被捕获,你会得到一个Abort,Retry或Ignore框。
Sub DeleteAllFilesInDir(ByVal pathName As String)
On Error GoTo errorHandler
Dim fileName As String
If Len(pathName) > 0 Then
If Right(pathName, 1) <> "\" Then pathName = pathName & "\"
End If
fileName = Dir(pathName & "*")
While Len(fileName) > 0
Kill pathName & fileName
fileName = Dir()
Wend
Exit Sub
errorHandler:
If Err.Number = 70 Then
Select Case MsgBox("Could not delete " & fileName & ". Permission denied. File may be open by another user or otherwise locked.", vbAbortRetryIgnore, "Unable to Delete File")
Case vbAbort:
Exit Sub
Case vbIgnore:
Resume Next
Case vbRetry:
Resume
End Select
Else
MsgBox "Error deleting file " & fileName & ".", vbOKOnly Or vbCritical, "Error Deleting File"
End If
End Sub
答案 3 :(得分:1)
看起来Scripting运行时FileSystemObject的DeleteFile方法也支持通配符,因为这对我有用:
Dim fs As New Scripting.FileSystemObject
fs.Deletefile "C:\Temp\*.jpg", true
这种方法的控制力比@Corazu提出的方法要少,但在某些情况下可能会有一些效用。