How to remove directory (in Four ways)
Posted on January 4, 2009
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | 'File/Folder Handling - How to remove directory (in Four ways) 'Using RmDir: Public Sub DeleteFolderUsingRmDir(ByVal sFolderName As String) 'This function deletes an existing empty directory. 'It will show error if the folder is not deleted/empty/exist. RmDir sFolderName End Sub 'Using FSO Public Sub DeleteFolderUsingFSO(ByVal sFolderName As String) 'Set a reference to "Microsoft Scripting Runtime" 'This function deletes an existing directory even if it is not empty. 'It will show error if the folder is not deleted/exist. Dim FSO As Scripting.FileSystemObject Set FSO = New Scripting.FileSystemObject FSO.DeleteFolder sFolderName Set FSO = Nothing End Sub 'Using API: Private Declare Function RemoveDirectory Lib "kernel32" Alias "RemoveDirectoryA" _ (ByVal lpPathName As String) As Long Public Sub DeleteFolderUsingAPI(ByVal sFolderName As String) 'This function deletes an existing empty directory. 'It will not show any error if the folder is not deleted/empty/exist. RemoveDirectory sFolderName End Sub 'Using Dos Command: Public Sub RemoveDirectory(ByVal sDir As String) Shell "Cmd.exe /C Rmdir /S /Q " & sDir End Sub 'How can I call this sub-routine 'Call RemoveDirectory("C:\Temp\Test\") 'Using Dir: 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 'How can I call this function 'Call DelTree("C:\Temp\Test\") |