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
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.

  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)


With fop
  .wFunc = FO_DELETE
  .pFrom = Filename
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.