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 deleted!")
Catch error As IOException
MessageBox(error.Message)
End Try

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

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

Var returnCode, lastErr, itemCount As Integer
Var files(), dirs() 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 deleting them right away!
itemCount = theFolder.Count
For i As Integer = 1 To itemCount
Var f As FolderItem
f = theFolder.TrueItem(i)
If f <> Nil Then
If f.Directory Then
dirs.Append(f)
Else
files.Append(f)
End If
End If
Next

// Now delete the files
For Each f As FolderItem In files
f.Remove
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 If
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 = DeleteEntireFolder(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 If
End If
Next

If returnCode = 0 Then
// We‘re done without error, so the folder should be empty and we can delete it.
theFolder.Remove
returnCode = theFolder.LastErrorCode
End If

Return returnCode
End Function