Go4Expert (http://www.go4expert.com/)
-   Visual Basic [VB] (http://www.go4expert.com/articles/visual-basic-tutorials/)
-   -   Send to Recycle Bin with VB (http://www.go4expert.com/articles/send-recycle-bin-vb-t3996/)

pradeep 23Apr2007 16:17

Send to Recycle Bin with VB
In VB you can use the Kill statement to delete files quickly but you lose the ability to retrieve the files easily. We will see how to delete files to the Recycle Bin that can be recovered.

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

Code: VB

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

All times are GMT +5.5. The time now is 22:57.