ABOUT RECYCLE BIN
Recycle Bin is a feature of Microsoft Windows that allows you to send files and folders to a local "recycle bin", so that files can be restored before being deleted from the Windows system.
Microsoft released Recycle Bin with Windows 95, a long time ago.
Since Windows 95, nothing but the icon has really changed.
Windows 95
Windows 7
Windows 10
Initially, to delete files and folders programmatically you need to call an API from Shell32.dll.
DELETING TO RECYCLE BIN USING C#
Sadly, C# doesn't have a native API to delete files and folder to Recycle Bin.
BUT, Visual Basic HAS!!!
And you can call Visual Basic FROM C# as well.
THE CODE
So, let's go to the code.
Just copy and paste this code to a file named ExtensionDeleteToRecycleBin.cs or other name if you like.
- namespace System.IO
- {
-
-
-
- public static class ExtensionDeleteToRecycleBin
- {
-
-
-
-
-
-
- public static void FileRecycle(this string file)
- =>
- Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile(file,
- Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs,
- Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin);
-
-
-
-
-
-
- public static void DirectoryRecycle(this string path)
- =>
- Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory(path,
- Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs,
- Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin);
-
-
- }
- }
HOW TO USE
You need to make a reference to the namespace System.IO in your cs file.
For my use only, I just let on the namespace System, so it's easier to call it.
- using System;
- using System.IO;
-
- namespace AppDebugTests
- {
- class Program
- {
- [STAThread]
- static void Main(string[] args)
- {
- "C:\\MyFolder2Delete".DirectoryRecycle();
-
- "C:\\MyFile2Delete.txt".FileRecycle();
-
- Console.ReadKey();
-
- }
-
- }
- }
Another way to use it:
- var files = new[] { "File1.txt", "File2.txt" };
-
- foreach (var file in files)
- $"C:\\{file}".FileRecycle();
TAKE CARE
Files with more than 2GB and network resources don't go to the recycle bin!
Only local files can be sent to the recycle bin.
You can add an extension to delete forever by just changing a parameter:
Microsoft.VisualBasic.FileIO.RecycleOption.DeletePermanently
- public static void DirectoryDelete4Ever(this string path) =>
- Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory(path,
- Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs,
- Microsoft.VisualBasic.FileIO.RecycleOption.DeletePermanently);
CONCLUSION
Deleting from the recycle bin is a way to avoid losing files, especially if your application processes original documents.
I'm in love with extension methods because we don't need to create variables to do something, we can do something directly from a const string.
Happy coding.