views:

564

answers:

3

Hi all,

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

Thanks

+3  A: 

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
alex
I'm getting an error "User-Defined Type not defined" on "Dim oFs As New FileSystemObject"
zSysop
That's because you'll need to add the reference to the FileSystemObject to use it..I don't remember what the exact reference name is though.
Corazu
"To use FileSystemObject, you must select the Microsoft Scripting Run-time in the Project References dialog box for your project."According to:http://support.microsoft.com/kb/186118
alex
A: 

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
Corazu
MarkJ
Yea..I upvoted that one as well.
Corazu
+2  A: 

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.

MarkJ
I always seem to overcomplicate things..I should have remembered this.
Corazu