Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleDelete a directory and everything it contains
DescriptionThis 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.
Keywordsfile, directory, dir, remove, delete
CategoriesFiles 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
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated