BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Input / Output
.NET 1.1+

Recycling Files and Folders Part 2

The second part of this two-part article revisits sending files and folders to the Windows Recycle Bin. In the first part we used the VisualBasic namespace to perform this task. In the second part we will make use of the Windows API through P/Invoke.

Recycling Multiple Files Using Wildcards

The SHFileOperation function allows you to send multiple files to the Recycle Bin in a single call. This is achieved by using the standard wildcard characters for file operations. An asterisk (*) indicates that any series of characters will be matched. A question mark (?) matches any single character. The wildcards can be combined with text to define a pattern to match within the filename portion of the pFrom field. You may not use wildcards in the path element.

For example, to recycle all files from the "c:\Recycle" folder, execute the following command. As before, you can change the flags to modify the behaviour:

SHFILEOPSTRUCT operation = new SHFILEOPSTRUCT();
operation.wFunc = FO_DELETE;
operation.pFrom = @"c:\Recycle\*.*" + "\0\0";
operation.fFlags = FOF_ALLOWUNDO;
int result = SHFileOperation(ref operation);

Sending Folders to the Recycle Bin

Finally, SHFileOperation can be used to send entire folders to the Recycle Bin. This deletes the folder and all of its contents with a single call to the function. To specify that you wish to remove a folder, simply provide the folder name in the pFrom field of the SHFILEOPSTRUCT structure. The folder name should not include a trailing backslash but, as with filenames, it should be double null-terminated.

SHFILEOPSTRUCT operation = new SHFILEOPSTRUCT();
operation.wFunc = FO_DELETE;
operation.pFrom = @"c:\Recycle" + "\0\0";
operation.fFlags = FOF_ALLOWUNDO;
int result = SHFileOperation(ref operation);
21 May 2009