Move a FolderItem to the trash

From REALbasicWiki

Jump to: navigation, search
Overall article skill Skill ranges from beginner (green) to expert (red)

Moving a FolderItem to the trash is a bit trickier than just f.MoveFileTo TrashFolder because:

  • There are several trashes (at least one per volume)
  • ...but usually not on network volumes
  • There may already be an item with the same name in the trash

[edit] Solution 1 - move the item yourself

// Return an error code <> 0 if the item could not be move to the Trash

if theItem <> nil and theItem.Exists then

// 1. Let‘s get a reference to the trash on the same volume as theItem
dim theTrash as FolderItem = theItem.TrashFolder
if theTrash=nil or (not theTrash.IsWriteable) then
return 1000 // An error code. Choose the one you want
end if

// 2. Do we need to rename the item when moving it ?

// Let‘s first try the same name as theItem
dim g as FolderItem = theTrash.Child( theItem.Name )
theItem.MoveFileTo g

if theItem.Exists then // the move failed
// We need to rename the file in the trash
dim idx as integer = 0
do
idx = idx + 1
g = theTrash.Child( theItem.NameWithoutExtension + " - " + Str( idx ) + "." + theItem.Extension )
loop until g<>nil and (not g.exists)
theItem.MoveFileTo g
end if

if theItem.Exists then
// The move still failed
return 1001 // An error code. Choose the one you want
end if

end if

For the NameWithoutExtension method, see Split name and extension of a FolderItem.

[edit] Solution 2 - ask the Mac OS Finder to do it

Protected Sub MoveToTrash(items() as FolderItem)
// Note: This function _might_ fail, e.g. if the deletion requires special permissions that
// the user does not have.
//
// There is one maybe unwanted problem with this routine:
// If the item is on a disk where there&apos;s no general Trash, the user won&apos;t be told and the
// file will be deleted immediately. You might like to have the Finder show a "this item will be
// deleted immediately - continue?" dialog like it happens when you delete an item in the
// Finder, but this is not happening here, unfortunately.

#if TargetMacOS
if items.Ubound >= 0 then
dim ok as Boolean
dim ae as AppleEvent
ae = NewAppleEvent( "core", "move", "MACS" )
dim list as new AppleEventDescList
for each f as FolderItem in items
if f <> nil then
list.AppendFolderItem (f)
end if
next
ae.DescListParam("----") = list
ae.ObjectSpecifierParam( "insh" ) = GetPropertyObjectDescriptor( Nil, "trsh" )
&apos;ae.SetNullParam( "alrp" ) // keyAEReplacing
ok = ae.send
if not ok then
break
end
end if
#endif
End Sub
Personal tools
related