Make your own free website on Tripod.com

Delete Directory And All Its Content

'This example imitate the DOS deltree command.
'Insert the following code to your form:

Private Sub Form_Load()
'Replace the 'C:\MyDir' below with the name of the directory you want to delete.
x = DelTree("C:\MyDir")
Select Case x
Case 0: MsgBox "Deleted"
Case -1: MsgBox "Invalid Directory"
Case Else: MsgBox "An Error was occured"
End Select
End Sub

Function DelTree(ByVal strDir As String) As Long
Dim x As Long
Dim intAttr As Integer
Dim strAllDirs As String
Dim strFile As String
DelTree = -1
On Error Resume Next
strDir = Trim$(strDir)
If Len(strDir) = 0 Then Exit Function
If Right$(strDir, 1) = "\" Then strDir = Left$(strDir, Len(strDir) - 1)
If InStr(strDir, "\") = 0 Then Exit Function
intAttr = GetAttr(strDir)
If (intAttr And vbDirectory) = 0 Then Exit Function
strFile = Dir$(strDir & "\*.*", vbSystem Or vbDirectory Or vbHidden)
Do While Len(strFile)
If strFile <> "." And strFile <> ".." Then
  intAttr = GetAttr(strDir & "\" & strFile)
  If (intAttr And vbDirectory) Then
   strAllDirs = strAllDirs & strFile & Chr$(0)
  Else
   If intAttr <> vbNormal Then
    SetAttr strDir & "\" & strFile, vbNormal
    If Err Then DelTree = Err: Exit Function
   End If
   Kill strDir & "\" & strFile
   If Err Then DelTree = Err: Exit Function
  End If
End If
strFile = Dir$
Loop
Do While Len(strAllDirs)
x = InStr(strAllDirs, Chr$(0))
strFile = Left$(strAllDirs, x - 1)
strAllDirs = Mid$(strAllDirs, x + 1)
x = DelTree(strDir & "\" & strFile)
If x Then DelTree = x: Exit Function
Loop
RmDir strDir
If Err Then
DelTree = Err
Else
DelTree = 0
End If
End Function

Go Back