Developer

Write your VB apps so deleted files are recoverable

Your VB app might enable users to delete files, but what if a deleted file needs to be recovered? Find out about an API that sends files to the Recycle Bin rather than to a permanent graveyard.


You'll often need to equip your VB applications with a way for users to delete files they no longer require. Unfortunately, the easiest way to handle this—using the Kill function—is a one-way ticket. If users inadvertently delete a file, or if you need a deleted file for debugging purposes, there's no way to get it back.

Kill is convenient for developers because it doesn’t require an API call. All you have to do is pass a pathname for the file or files as a string expression to the function—for example, Kill (App.Path & "\1.txt")—and the files are deleted. But if you want to give your users a safety net and make sure that their files are recoverable, you can take another approach. Instead of using the Kill function, have your apps send deleted files to the Recycle Bin. Here's a look at how it works.

A trip to the Recycle Bin
The key to this technique is the SHFileOperation function, which is exported by Shell32.dll. SHFileOperation is supported under Windows 95/98/Me/NT4.0/2000 and allows copying, moving, renaming, and deleting objects in the file system. You can also use it to delete files by sending them to the Recycle Bin so that users can restore them if necessary.

The API
By calling SHFileOperation, you can leverage the existing dialogs for moving files and providing user feedback about the status of the process. To use the SHFileOperation function in a Visual Basic program, you must include the following Declare statement:
Public Declare Function SHFileOperation Lib _
   "shell32.dll" Alias "SHFileOperationA" (lpFileOp _
   As SHFILEOPSTRUCT) As Long

The SHFileOperation function returns 0 when the operation is successful and any nonzero value when an error occurs.

The function requires one argument, a pointer to a SHFILEOPSTRUCT structure. This structure contains information the SHFileOperation function needs to perform the requested file operation.

For Visual Basic, the format of the SHFILEOPSTRUCT structure looks like this:
Public Type SHFILEOPSTRUCT
     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

The elements of the structure
Table A describes each of the elements of the SHFILEOPSTRUCT structure. Sending files to the Recycle Bin requires setting two options: FO_DELETE and FO_ALLOWUNDO.
Table A
Element Description/possible values
hwnd Window handle to the dialog box to display information about the status of the file operation
wFunc

The type of operation to be performed:
FO_COPYcopies files specified in pFrom member to the location specified in pTo member
FO_DELETEDeletes files specified in pFrom
FO_MOVE—Moves files specified in pFrom to the location specified in pTo
FO_RENAME—Renames files specified in pFrom

pFrom Address of a buffer to specify source file names. Multiple names must be null-separated. The list of names must be double null-terminated.
pTo Address of a buffer to contain the name of the destination file or directory. The buffer can contain multiple destination file names if the fFlags member specifics FOF_MULTIDESTFILES. Multiple names must be null-separated. The list of names must be double null-terminated.
fFlags Flags that control the file operation. More than one flag can be used:
FOF_ALLOWUNDO—Preserve Undo information
FOF_FILESONLY—Perform the oepration on files only if a wildcard file name (*.*) is specified
FOF_MULTIDESTFILES—The pTo member specifies multiple destination files (one for each source file) instead of one directory where all source files are to be sent.
FOF_NOCONFIRMATION—Respond with Yes to All for any dialog box that is displayed
FOF_NOCONFIRMMKDIR—Does not confirm the creation of a new directory if the operation requires one to be created
FOF_NOERRORRUI—No user interface will be displayed if an error occurs.
FOF_RENAMEONCOLLISION—Provide the file being operated on a new name in a move, copy, or a rename operation if a file with the target name already exists
FOF_SILENT—Does not display a progress dialog box
FOF_SIMPLEPROGRESS—Displays a progress dialog box but not file names
FOF_WANTMAPPINGHANDLE—If FOF_RENAMEONCOLLISION is specified, the hNameMappings will be filled in if any files were renamed.
fAnyOperationsAborted Value that receives True if the user aborted file operations befor they were completed; returns False otherwise
hNameMappings Handle to file name mapping object that contains an array of SHNAMEMAPPING structures. Each structure contains the old and new path for each file that was moved, copied, or renamed. Only if fFlags member includes the FOF_WANTMAPPINGHANDLE flag. The handle must be freed by using the SHFreeNameMappings function.
IpszProgressTitle Address of a string to use as the title of a progress dialog box. Only used if fFlags includes the FOF_SIMPLEPROGRESS flag.
Elements of SHFILEOPSTRUCT

Code demo
Let’s create a simple VB project to send a file to the Recycle Bin. For this sample function to work as designed, you'll need to deselect the Recycle Bin option to remove files immediately when deleted, as shown in Figure A.

Figure A
Recycle Bin Properties screen

  1. Fire up VB and start a new project.
  2. Create a module and add the following code to it:
Option Explicit
 
Public Type SHFILEOPSTRUCT
     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
 
Public Declare Function SHFileOperation Lib _
"shell32.dll" Alias "SHFileOperationA" (lpFileOp _
As SHFILEOPSTRUCT) As Long
 
Public Const FO_DELETE = &H3
Public Const FOF_ALLOWUNDO = &H40
  1. Add a command button to your form and call it cmdSendToRecycleBin.

Your screen should now look like Figure B.

Figure B
Sample form

  1. Add the following code to the cmdSendToRecycleBin Click event:
    Dim SHop As SHFILEOPSTRUCT
    Dim strFile As String
 
    strFile = App.Path & "\hello.txt"
 
    With SHop
         .wFunc = FO_DELETE
         .pFrom = strFile
         .fFlags = FOF_ALLOWUNDO
    End With
 
    SHFileOperation SHop
  1. Modify the filename and location in strFile = App.Path & "\hello.txt" to reflect the file you want to send to the Recycle Bin. If the file is located in the same directory as the VB project, you can leave App.Path and just change the name of the file.
  2. Press [Ctrl][F5] to run the project.
  3. Click Send To Recycle Bin, and your screen should look like Figure C. Select Yes, and the file will be moved to the Recycle Bin.

Figure C
Sample output


More fun with VB and APIs
In this sample, we used the SHFileOperation API to send a specified file to the Recycle Bin, allowing users to restore files if necessary. Next time, we will look at some other API functions that come in handy for application development—functions that will enable users to log off, restart, or shut down their computers.

Editor's Picks