|
|
Title | Delete a directory and everything it contains |
Description | This example shows how to delete a directory and everything it contains in Visual Basic 6. It searches the directory for subdirectories and recursively removes them first. |
Keywords | file, directory, dir, remove, delete |
Categories | Files and Directories |
|
|
The DeleteDirectory subroutine makes a list of the files and subdirectories in this directory. It then loops through the list, deleting the files and recursively calling itself to delete the subdirectories. It then deletes its directory.
|
|
' Delete this directory and all the files it contains.
Private Sub DeleteDirectory(ByVal dir_name As String)
Dim file_name As String
Dim files As Collection
Dim i As Integer
' Get a list of files it contains.
Set files = New Collection
file_name = Dir$(dir_name & "\*.*", vbReadOnly + _
vbHidden + vbSystem + vbDirectory)
Do While Len(file_name) > 0
If (file_name <> "..") And (file_name <> ".") Then
files.Add dir_name & "\" & file_name
End If
file_name = Dir$()
Loop
' Delete the files.
For i = 1 To files.Count
file_name = files(i)
' See if it is a directory.
If GetAttr(file_name) And vbDirectory Then
' It is a directory. Delete it.
DeleteDirectory file_name
Else
' It's a file. Delete it.
lblStatus.Caption = file_name
lblStatus.Refresh
SetAttr file_name, vbNormal
Kill file_name
End If
Next i
' The directory is now empty. Delete it.
lblStatus.Caption = dir_name
lblStatus.Refresh
' Remove the read-only flag if set.
' (Thanks to Ralf Wolter.)
SetAttr dir_name, vbNormal
RmDir dir_name
End Sub
|
|
|
|
|
|