Advertisement
2_2002-2004 Files/ File Controls/ Input/ Output #116330

Directory Cleaner (recursively)

This function attempts to delete all files and subdirectories of the given directory name, and leaves the given directory intact, but completely empty. If the Kill command generates an error (i.e. file is in use by another process - permission denied error), then that file and subdirectory will be skipped, and the program will continue (On Error Resume Next). EXAMPLE CALL: ClearDirectory "C:\Temp\"

AI

AI Summary: This codebase represents a historical implementation of the logic described in the metadata. Our preservation engine analyzes the structure to provide context for modern developers.

Source Code
original-source
Private Sub ClearDirectory(psDirName)
'This function attempts to delete all files
'and subdirectories of the given 
'directory name, and leaves the given 
'directory intact, but completely empty.
'
'If the Kill command generates an error (i.e.
'file is in use by another process - 
'permission denied error), then that file and
'subdirectory will be skipped, and the 
'program will continue (On Error Resume Next).
'
'EXAMPLE CALL:
' ClearDirectory "C:\Temp\"
Dim sSubDir
If Len(psDirName) > 0 Then
 If Right(psDirName, 1) <> "\" Then
 psDirName = psDirName & "\"
 End If
 'Attempt to remove any files in directory
 'with one command (if error, we'll 
 'attempt to delete the files one at a
 'time later in the loop):
 On Error Resume Next
 Kill psDirName & "*.*"
 DoEvents
 
 sSubDir = Dir(psDirName, vbDirectory)
 Do While Len(sSubDir) > 0
 'Ignore the current directory and the
 'encompassing directory:
 If sSubDir <> "." And _
  sSubDir <> ".." Then
  'Use bitwise comparison to make 
  'sure MyName is a directory:
  If (GetAttr(psDirName & sSubDir) And _
  vbDirectory) = vbDirectory Then
  
  'Use recursion to clear files
  'from subdir:
  ClearDirectory psDirName & _
   sSubDir & "\"
  'Remove directory once files
  'have been cleared (deleted)
  'from it:
  RmDir psDirName & sSubDir
  DoEvents
  
  'ReInitialize Dir Command
  'after using recursion:
  sSubDir = Dir(psDirName, vbDirectory)
  Else
  'This file is remaining because
  'most likely, the Kill statement
  'before this loop errored out
  'when attempting to delete all
  'the files at once in this
  'directory. This attempt to
  'delete a single file by itself
  'may work because another 
  '(locked) file within this same
  'directory may have prevented
  '(non-locked) files from being
  'deleted:
  Kill psDirName & sSubDir
  sSubDir = Dir
  End If
 Else
  sSubDir = Dir
 End If
 Loop
End If
End Sub
Original Comments (3)
Recovered from Wayback Machine