2009-09-23 61 views

回答

7

一号线,使用VB6声明Kill

Kill "c:\doomed_dir\*.*" 

help topic says“在Microsoft Windows,杀支持使用多字符(*)和单字符(?)通配符的指定多个文件“。

另外 - 我宁愿避免Microsoft脚本运行时(包括FileSystemObject)。根据我的经验,在用户机器上偶尔会出现这种情况,这可能是因为他们的IT部门对病毒有偏见。

+0

我总是看起来过于复杂......我应该记住这一点。 – Corazu 2009-09-23 17:40:37

+1

在Access 2000中,如果该目录中的一个文件被锁定(或打开),则使用带有Kill命令的“*。*”通配符将会失败。 – Spidermain50 2011-09-09 19:19:54

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 
+0

我在“Dim oFs As New FileSystemObject”上收到错误“用户定义类型未定义” – zSynopsis 2009-09-23 15:54:26

+0

这是因为您需要添加对FileSystemObject的引用以使用它..我不记得是什么确切的参考名称是。 – Corazu 2009-09-23 16:05:45

+0

“要使用FileSystemObject,您必须在Project References对话框中为您的项目选择Microsoft Scripting Run-time。”根据: http://support.microsoft.com/kb/186118 – Alex 2009-09-24 08:40:36

2

我没有测试过所有情况,但它应该工作。它应该删除每个文件,如果文件被锁定或者你没有访问权限,你应该得到错误70被捕获,你会得到一个中止,重试或忽略框。

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 
+0

+1同情,因为我不认为这当之无愧-1。虽然“Kill”&pathname&“\ *。*”肯定比较短。 – MarkJ 2009-09-24 09:08:45

1

这似乎是脚本运行FileSystemObject的公司的DeleteFile方法也支持通配符,因为这对我的作品:

Dim fs As New Scripting.FileSystemObject 
fs.Deletefile "C:\Temp\*.jpg", true 

这种方法比@Corazu建议的方法控制较少,但可能在某些一些实用案例。

相关问题