C#: Delete a file to the recycle bin

May 5, 2008 by

I had a friend ask me yesterday what the easiest/best way to delete a file to the recycle bin was, in C# that is.  I knew about SHFileOperation, but I didn’t know if .NET 2.0 had native support for sending files to the recycle bin.  As it turns out, there are two ways in which you can move files to the recycle bin.  Microsoft has included the support in the Microsoft.VisualBasic namespace, and referencing the Microsoft.VisualBasic assembly will allow you to use that function directly.

Deleting a file using Managed code in C# or VB.NET:

(Remember to add a reference to Microsoft.VisualBasic)

using Microsoft.VisualBasic;
string path = @"c:\myfile.txt";
FileIO.FileSystem.DeleteDirectory(path, FileIO.UIOption.OnlyErrorDialogs, .RecycleOption.SendToRecycleBin);

The other alternative is to use COM Interop and P/Invoke the SHFileOperation from the Windows shell32.dll.

Deleting a file using P/Invoke in C#:

I have written a class that provides methods to easily specify how the file should be sent to the recycle bin.  SHFileOperation can take flags, which I have put into an enum and commented.  These flags define how the operation should be executed.

  • FOF_SILENT – Do not show the “Recycling…” dialog.
  • FOF_NOCONFIRMATION – Do not prompt the use for confirmation of the operation.
  • FOF_ALLOWUNDO – This is the option that specifies that the file should be sent to the recycle bin.  It is added by default in each Send method.
  • FOF_SIMPLEPROGRESS – This option will surpress the display of the names of the files that are being deleted.
  • FOF_NOERRORUI – This option will suppress any errors encountered during the operation.
  • FOF_WANTNUKEWARNING – Adding this flag will allow a dialog to allow the user to cancel removing large files permanently, if they are too large for the recycle bin.

Any one of these flags can be added to change the operation.

Methods provided by the RecycleBin class:

  • bool Send(string path)
  • bool Send(string path, FileOperationFlags flags)
  • static bool SendSilent(string path)

The first will simply send a path to the bin while showing the dialog, but surpressing the confirmation.

The second will allow you to customize the flags for the file operation, the only flag set for you is FOF_ALLOWUNDO. Flags can be combined with the | operator. e.g. FOF_NOERRORUI | FOF_SIMPLEPROGRESS.

The third, and probably most commonly used, will surpress all errors and warnings, and not show the user any operation is in progress.

Code Sample:

SendToRecycleBin.zip [ZIP] [Visual Studio 2008] (43KB)

Update – 04/18/2010:  Updated sample for x64 compatibility.