Delete a non-empty folder
From REALbasicWiki
| Overall article skill | ✭ |
Method FolderItem.Delete() will work on folders only if the folder is empty.
If you want to delete a folder, you must then delete its content first. But if your folder contains subfolders, then you must empty the subfolders and delete them before. And subfolders can also contain subfolders... This is exactly the kind of work for a recursive method, i.e. a method which calls itself.
The following DeleteFolder function looks complex but should take care of any eventualities, such as the possibility of items being added or deleted by other process while the function iterates the folder contents. It also offers an optional mode in which it tries to delete as much as possible (forced delete), even if some items fail to be deleted.
Function DeleteFolder(theFolder as FolderItem, continueIfErrors as Boolean = false) As Integer
// Returns an error code if it fails, or zero if the folder was deleted successfully
dim returnCode, lastErr, itemCount as integer
dim files(), dirs() as FolderItem
if theFolder = nil or not theFolder.Exists() then
return 0
end
// Collect the folder‘s contents first.
// This can be faster than collecting them in reverse order and deleting them right away
// (this is the case with certain file systems that are optimized for forward iteration)
itemCount = theFolder.Count
for i as integer = 1 to itemCount
dim f as FolderItem
f = theFolder.TrueItem( i )
if f <> nil then
if f.Directory then
dirs.Append f
else
files.Append f
end
end
next
// Now delete the files
for each f as FolderItem in files
f.Delete
lastErr = f.LastErrorCode // Check if an error occurred
if lastErr <> 0 then
if continueIfErrors then
if returnCode = 0 then returnCode = lastErr
else
// Return the error code if any. This will cancel the deletion.
return lastErr
end
end if
next
redim files(-1) // free the memory used by the files array before we enter recursion
// Now delete the directories
for each f as FolderItem in dirs
lastErr = DeleteFolder( f, continueIfErrors )
if lastErr <> 0 then
if continueIfErrors then
if returnCode = 0 then returnCode = lastErr
else
// Return the error code if any. This will cancel the deletion.
return lastErr
end
end if
next
if returnCode = 0 then
// We‘re done without error, so the folder should be empty and we can delete it.
theFolder.Delete
returnCode = theFolder.LastErrorCode
if returnCode = 0 and theFolder.Exists then
// some unknown reason prevented the folder from being deleted
returnCode = -1
end
end
return returnCode
End Function
[edit] See also
- Delete items from a list - this page explains why an array of FolderItems is created before deleting them.
- Delete a folder - an alternative approach
