The following code example needs at least Mountain Lion to work. It creates a file and moves it to trash. If a file with the same filename already exists in trash, the file will be renamed to a unique filename before moving it to trash. You can simply prove it by executing this program a second time - the program moved to trash will obtain a modified filename...
I have tested the code example successfully on Mountain Lion and Yoesmite.
The
NSWorkspace method
recycleURLs:completionHandler: proposed by Wilbert won't work in PureBasic because it utilizes a completion handler block. This is a technique which I still haven't been able to implement in PureBasic. It would be very interesting if Wilbert knows a way...
The
NSWorkspace method
performFileOperation:source:destination:files:tag: would indeed be an alternative that even should work with MacOS versions older than Mountain Lion!
Code: Select all
EnableExplicit
Define Error.I = CocoaMessage(0, 0, "NSError alloc")
Define Result.I
Define TestFile.S = GetTemporaryDirectory() + "Test.Txt"
Define TestFileURL.I
Define TrashFileURL.I
If OSVersion() < #PB_OS_MacOSX_10_8
MessageRequester("Error",
"Sorry, but this program needs at least Mountain Lion!")
End
EndIf
If CreateFile(0, TestFile)
WriteString(0, "This file should be moved to the trash can!")
CloseFile(0)
TestFileURL = CocoaMessage(0, 0,
"NSURL fileURLWithPath:$", @TestFile,
"isDirectory:", #NO)
TrashFileURL = CocoaMessage(0, 0, "NSURL alloc")
If TestFileURL
If TrashFileURL
Result = CocoaMessage(0, CocoaMessage(0, 0, "NSFileManager defaultManager"),
"trashItemAtURL:", TestFileURL,
"resultingItemURL:", @TrashFileURL,
"error:", @Error)
If Result = #YES
MessageRequester("Success", "The file '" + GetFilePart(TestFile) +
"'" + #CR$ + "was successfully moved to trash as file" + #CR$ + "'" +
PeekS(CocoaMessage(0, CocoaMessage(0, TrashFileURL,
"lastPathComponent"), "UTF8String"), -1, #PB_UTF8) + "'")
Else
MessageRequester("Error", "Moving file " + GetFilePart(TestFile) +
" to trash has failed!" + #CR$ + #CR$ + PeekS(CocoaMessage(0,
CocoaMessage(0, Error, "localizedDescription"), "UTF8String"),
-1, #PB_UTF8))
EndIf
CocoaMessage(0, TrashFileURL, "release")
EndIf
CocoaMessage(0, TestFileURL, "release")
EndIf
EndIf