Delete all files within a directory vb6

廉价感情. 提交于 2020-01-03 18:43:13

问题


I was wondering if anyone could help me with a vb6 function that would delete all files within a directory (excluding subdirectories).


回答1:


One line, using the VB6 statement Kill

Kill "c:\doomed_dir\*.*"

The help topic says "In Microsoft Windows, Kill supports the use of multiple-character (*) and single-character (?) wildcards to specify multiple files".

As an aside - I prefer to avoid the Microsoft Scripting Runtime (including FileSystemObject). In my experience it's occasionally broken on user machines, perhaps because their IT department are paranoid about viruses.




回答2:


I believe this should work:

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



回答3:


I haven't tested every scenario but it should work. It should delete every file and if the file is locked or you don't have access you should get Error 70 which is caught and you get an Abort, Retry or Ignore box.

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



回答4:


It would seem that the Scripting runtime FileSystemObject's DeleteFile method also supports wildcards as this works for me:

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

This approach has less control than the approach suggested by @Corazu, but may have some utility in certain cases.



来源:https://stackoverflow.com/questions/1466766/delete-all-files-within-a-directory-vb6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!