Delete files or folders to recycle bin in C#
Sadly C# doesn’t have the required libraries in place to aid the users or the developers to send files or folders directly to the recycle bin.
System.IO.Directory.Delete() simply delete the path without allowing for the action to be undone.
Luckily there are two ways this can be resolved. Either by using the Windows API
SHFileOperation function or by referencing
Microsoft.VisualBasic and using the
Personally I prefer the
Microsoft.VisualBasic approach as the code looks much cleaner and is more readable to me but I will demonstrate how both methods can be implemented either way.
The Microsoft.VisualBasic approach:
Microsoft.VisualBasic in your project and simply call
depending if you want to delete a file or a folder.
The SHFileOperation approach:
Add and initialize the following variables, struct and DllImport in the class you will be doing the deletion from.
private const int FO_DELETE = 0x0003;
private const int FOF_ALLOWUNDO = 0x0040; // Preserve undo information, if possible.
private const int FOF_NOCONFIRMATION = 0x0010; // Show no confirmation dialog box to the user
// Struct which contains information that the SHFileOperation function uses to perform file operations.
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct SHFILEOPSTRUCT
public IntPtr hwnd;
public int wFunc;
public string pFrom;
public string pTo;
public short fFlags;
public bool fAnyOperationsAborted;
public IntPtr hNameMappings;
public string lpszProgressTitle;
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);
DeleteFileOrFolder() method which will delete the file or folder you will provide as argument
public static void DeleteFileOrFolder(string path)
SHFILEOPSTRUCT fileop = new SHFILEOPSTRUCT();
fileop.wFunc = FO_DELETE;
fileop.pFrom = path + '\0' + '\0';
fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;
Then simply call the method with the path you want to delete: