Developer

VB6 Tip: Deleting files to the Recycle Bin from within a VB6 application

In Visual Basic 6, with the right API function, you can delete a file to the Windows Recycle Bin, where it can be restored later if necessary.

You can use Visual Basic's Kill statement to delete files from a disk. You can also use the methods that are associated with the FileSystemObject class in the Windows Scripting Runtime. Both of these methods have the shortcoming that they delete a file permanently; in other words, they don't delete the file to the Windows Recycle Bin, from which it can be restored.

To delete a file to the Recycle Bin, use the SHFileOperation API function. This function takes as its one argument a user-defined type (UDT) that contains information (such as the filename) about the operation to perform. (This API function has many other uses besides deleting files, but these are beyond the scope of this tip.)

You can see the definition of the UDT in the sample code that follows. To delete a file, you must include three pieces of information in the UDT: the name of the file, a flag specifying a delete operation, and another flag specifying that the delete is to be undoable.

The following code shows how this is done. Place this code in a code module in your project, and then call the DeleteFileToRecycleBin procedure, passing the name (including the path) of the file to be deleted.

Private Type SHFILEOPTSTRUCT
  hWnd As Long
  wFunc As Long
  pFrom As String
  pTo As String
  fFlags As Integer
  fAnyOperationsAborted As Long
  hNameMappings As Long
  lpszProgressTitle As Long
End Type

Private Declare Function SHFileOperation Lib "Shell32.dll" _
  Alias "SHFileOperationA" (lpFileOp As SHFILEOPTSTRUCT) As Long
 
Private Const FO_DELETE = &H3
Private Const FOF_ALLOWUNDO = &H40

Public Sub DeleteFileToRecycleBin(Filename As String)

Dim fop As SHFILEOPTSTRUCT

With fop
  .wFunc = FO_DELETE
  .pFrom = Filename
  .fFlags = FOF_ALLOWUNDO
End With

SHFileOperation fop

End Sub

If there's a problem, such as the file is read-only, the file isn't found, or it has insufficient permissions, an error message will appear. Otherwise, the file will be deleted. Depending on the system settings, a confirmation dialog box may or may not be displayed. By using this technique, you've added the safety of knowing that any files deleted by your program can be recovered if needed.

Peter Aitken has been programming with Visual Basic since Version 1.0. He has written numerous books and magazine articles on Visual Basic and other computer and programming topics.

Editor's Picks

Free Newsletters, In your Inbox