FolderItem.Remove

From Xojo Documentation

Method

FolderItem.Remove()

Supported for all project types and targets.

Removes/deletes the file or folder specified by the FolderItem.

Notes

This method irreversibly removes the file or folder from the volume it was stored on. If you are deleting a folder, it needs to be empty.

If the file could not be deleted, an IOException occurs. You can then check the IOException.ErrorNumber, IOException.Message or IOException.Reason to find out what went wrong (e.g. the file could still be in use, or it was locked, the directory was not empty, or the entire volume may have vanished in the mean time).

Examples

This example removes a specific file.

Var f As FolderItem
f = New FolderItem("Project Templates")
Try
f.Remove
MessageBox("File removed!")
Catch error As IOException
MessageBox(error.Message)
End Try

This example shows how to efficiently and correctly remove a folder and all its contents.

Function RemoveEntireFolder(theFolder As FolderItem, continueIfErrors As Boolean = False) As Integer
// Returns an error code if it fails, or zero if the folder was removed successfully

Var returnCode, lastError As Integer
Var files(), folders() As FolderItem

If theFolder = Nil Or Not theFolder.Exists Then
Return 0
End If

// Collect the folder‘s contents first.
// This is faster than collecting them in reverse order and removing them right away!
For Each item As FolderItem In theFolder.Children
If item.Exists Then
If item.IsFolder Then
folders.Add(item)
Else
files.Add(item)
End If
End If
Next

// Now remove the files
For Each file As FolderItem In files
Try
file.Remove
Catch error As IOException
If error.ErrorNumber <> 0 Then
If continueIfErrors Then
If returnCode = 0 Then returnCode = lastError
Else
// Return the error code if any. This will cancel the deletion.
Return lastError
End If
End If
End Try
Next

files.RemoveAll // free the memory used by the files array before we enter recursion

// Now remove the folders
For Each f As FolderItem In folders
lastError = RemoveEntireFolder(f, continueIfErrors)
If lastError <> 0 Then
If continueIfErrors Then
If returnCode = 0 Then returnCode = lastError
Else
// Return the error code if any. This will cancel the removal.
Return lastError
End If
End If
Next

If returnCode = 0 Then
// We‘re done without error, so the folder should be empty and we can remove it.
Try
theFolder.Remove
Catch error As IOException
returnCode = error.ErrorNumber
End Try
End If

Return returnCode
End Function