Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top