I'm trying to use SHFileOperation to delete a folder containing many subfolders, but it always says that it can't be deleted b/c the folder's not empty. But I thought that this function could do that... any ideas?
Printable View
I'm trying to use SHFileOperation to delete a folder containing many subfolders, but it always says that it can't be deleted b/c the folder's not empty. But I thought that this function could do that... any ideas?
Try this:
VB Code:
Option Explicit Private Type SHFILEOPSTRUCT hWnd As Long wFunc As Long pFrom As String pTo As String fFlags As Integer fAborted As Boolean hNameMaps As Long sProgress As String End Type Private Const FOF_NOCONFIRMATION = &H10 Private Const FO_DELETE = &H3 Private Const FOF_ALLOWUNDO = &H40 Private Const FOF_FILESONLY = &H80 ' On *.*, Do only files Private Declare Function SHFileOperation Lib "shell32.dll" Alias "SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long Public Function NuKill(Path As String, Optional Recycle As Boolean = True) As Boolean 'Nucleus 'Delete file(s) Or Folder(s) (including subdirectories) And optionally send To recycle bin 'In: Path of file/folder 'Out: Boolean indicating success If Right(Path, 1) = "\" Then Path = Left(Path, Len(Path) - 1) If Len(Dir$(Path)) <> 0 Or Len(Dir$(Path, vbDirectory)) <> 0 Then Dim SHFileOp As SHFILEOPSTRUCT With SHFileOp 'Delete the file .wFunc = FO_DELETE 'Select the file .pFrom = Path .fFlags = FOF_NOCONFIRMATION Or FOF_FILESONLY 'next optionally allow move To recycle bin 'which only works For whole folders Or single file operations 'it will Not send *.* Or *.txt To recycle bin 'due To built-in limitations In api Function If Recycle Then .fFlags = .fFlags Or FOF_ALLOWUNDO End With 'perform file operation NuKill = (SHFileOperation(SHFileOp) = 0) End If End Function
Usage:
VB Code:
Private Sub Command1_Click() 'NuKill "c:\tmp\book1.xls" 'delete Single file And send To recycle bin MsgBox NuKill("c:\tmp") 'delete folder And send To recycle bin 'NuKill "c:\temp",false" 'delete folder, don't send To recyle bin 'Next the limitations: 'Note you can use kill\*.* instead for single directory operations 'NuKill "c:\tmp\*" ' delete all files In folder can't send To recycle bin due To api Function limitation 'NuKill "c:\tmp\*.txt" ' delete all text files In folder, can't send To recyle bin due To api Function limitations End Sub
Thanks- that works!
:cool: