Highlights
All Snippets
Top 100 Snippets
Librarians
gbCodeLib

By Language
VB6
JavaScript
Perl
HTML
SQL
Java
DOS

GBIC >> Source Code >> Visual Basic >> Snippet

Delete a folder and its subfolders


'uses FileSystemObject ( must add reference to project to use)
'WARNING!  deleted folder and all children with no prompting

Dim fso As New FileSystemObject

'delete folder and all content
fso.DeleteFolder ( "c:\files" )

'verification code
If fso.FolderExists( "C:\Files" ) Then MsgBox "Folder Exists!"


'===========================
'alternate approach using only built-in VB functions
'makes a list of files/folder.  recursively calls itself for any folders it finds

' Delete this directory and all the files it contains.
Sub DeleteDirectory(FolderName As String )
    Dim FileName As String
    Dim Files As Collection
    Dim i As Integer

'get a list of files and folders in the chosen folder
    Set files = New Collection
   FileName = Dir$(FolderName & "\*.*" , vbReadOnly + vbHidden + vbSystem + vbDirectory)
    Do While Len(FileName) > 0
        If (FileName <> ".." ) And (FileName <> "." ) Then
           Files.Add FolderName & "\" & FileName
        End If
       FileName = Dir$()
   Loop

'delete the files (recursively call DeleteDirectory on folders)
    For i = 1 To Files.Count
       FileName = Files(i)
        ' See if it is a directory.
        If GetAttr(FileName) And vbDirectory Then
            'directory. delete it.
           DeleteDirectory FileName
        Else
            'file. delete it.
           SetAttr FileName, vbNormal
           Kill FileName
        End If
    Next i

   RmDir FolderName

End Sub