When working with files and folders in .NET applications on Windows, you may want to move items to the Recycle Bin instead of permanently deleting them (File.Delete, Directory.Delete). This allows users to recover accidentally deleted items. Here's how to do it 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);
}
This method works for both files and directories:
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!