Tag Archives: delete folder
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.File.Delete()
and 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 Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile()
and Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory()
methods.
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:
Reference Microsoft.VisualBasic
in your project and simply call
1 2 3 | Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile(@"C:\Users\CooLMinE\Desktop\test.txt", Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin); |
or
1 2 3 | Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory(@"C:\Users\CooLMinE\Desktop\test", Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin); |
depending if you want to delete a file or a folder.
Posted in C#.
Tagged C#, csharp, delete, delete file, delete folder, SHFileOperation, SHFILEOPSTRUCT, snippet, winforms