FolderItem.Delete

From Xojo Documentation
Jump to: navigation, search
Method

FolderItem.Delete()

Deletes the file or directory specified by the FolderItem.

Notes

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

To check if the deletion succeeded, check the LastErrorCode: If it's zero, deletion was successful, otherwise it contains an error code describing 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 deletes a specific file.

Dim f As FolderItem
f = GetFolderItem("Project Templates")
f.Delete
If f.LastErrorCode > 0 Then
MsgBox(Str(f.LastErrorCode))
Else
MsgBox("File deleted!")
End If

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

Dim returnCode, lastErr, itemCount As Integer
Dim 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
Dim 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.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 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.Delete
returnCode = theFolder.LastErrorCode
End If

Return returnCode
End Function
Personal tools
Namespaces

Variants
Actions
Main
Content
Starting Out
Dig Deeper
More Help
Toolbox
About