Following the discussion here: https://forum.xojo.com/56592-api2-folderitem-lasterrorcode i’ve updated an old method to use the API2 FolderItem.
It works fine but i am not 100% sure if i did everything as it should. Does anybody see issues with this code?
[code]Public Function DeleteEntireFolder(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
If continueIfErrors Then
Return 0
Else
Return 1 // ToBeFixed: Don't have the correct Code at hand, so i'm just returning something different then 0 for now...
End If
End If
// Collect the folders contents first.
// This is faster than collecting them in reverse order and deleting them right away!
itemCount = theFolder.Count
For i As Integer = 0 To itemCount -1
Dim f As FolderItem
f = theFolder.ChildAt(i)
If f <> Nil Then
If f.IsFolder Then
dirs.AddRow(f)
Else
files.AddRow(f)
End If
End If
Next
// Now delete the files
For Each f As FolderItem In files
Try
f.Remove
Catch err As IOException
If continueIfErrors Then
If returnCode = 0 Then
returnCode = err.ErrorNumber
End If
Else
// Return the error code if any. This will cancel the deletion.
Return err.ErrorNumber
End If
End Try
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
Try
lastErr = DeleteEntireFolder(f, continueIfErrors)
Catch err As IOException
If continueIfErrors Then
If returnCode = 0 Then
returnCode = err.ErrorNumber
End If
Else
// Return the error code if any. This will cancel the deletion.
Return err.ErrorNumber
End If
End Try
Next
If returnCode = 0 Then
// Were done without error, so the folder should be empty and we can delete it.
Try
theFolder.Remove
returnCode = 0
Catch err As IOException
returnCode = err.ErrorNumber
End Try
End If
Return returnCode
End Function
[/code]
Updated Code: https://forum.xojo.com/conversation/post/460954