Moving Files and Folders to Recycle Bin in .NET

 
 
  • Gérald Barré

When working with files and folders in .NET applications on Windows, you might need to move items to the Recycle Bin instead of permanently deleting them (File.Delete, Directory.Delete). This provides users with the ability to recover accidentally deleted items. Here's how you can accomplish this using the Windows Shell API:

C#
static void MoveToRecycleBin(string path)
{
  var shellType = Type.GetTypeFromProgID("Shell.Application", throwOnError: true)!;
  dynamic shellApp = Activator.CreateInstance(shellType)!;

  // https://learn.microsoft.com/en-us/windows/win32/api/shldisp/ne-shldisp-shellspecialfolderconstants?WT.mc_id=DT-MVP-5003978
  var recycleBin = shellApp.Namespace(0xa);

  // https://learn.microsoft.com/en-us/windows/win32/shell/folder-movehere?WT.mc_id=DT-MVP-5003978
  recycleBin.MoveHere(path);
}

You can use this method to move both files and directories to the Recycle Bin:

C#
MoveToRecycleBin(@"C:\path\to\file.txt");
MoveToRecycleBin(@"C:\path\to\directory");

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub