How to register a global hotkey for your application in C#

How to register a global hotkey for your application in C#

Register a hotkey for your application that can be triggered even if your form is minimized and does not have focus. More »

How to download a file in C# (progressbar and download speed)

How to download a file in C# (progressbar and download speed)

Learn how to download files in C# while displaying the percentage and the download speed. More »

UDP hole punching implementation in C#

UDP hole punching implementation in C#

Learn how to implement UDP hole punching so you can make your clients life a lot easier by not forcing them to open ports on their end. More »

 

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

or

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.

Add the DeleteFileOrFolder() method which will delete the file or folder you will provide as argument

Then simply call the method with the path you want to delete:

Share on FacebookTweet about this on TwitterShare on Google+Share on StumbleUponShare on LinkedInShare on RedditPin on PinterestShare on TumblrDigg thisPrint this pageEmail this to someone

2 Responses to Delete files or folders to recycle bin in C#

  1. Mohajana Dissanayaje says:

    how to delete multiple files with The SHFileOperation approach?

  2. pozycjonowanie says:

    Excellent post. I used to be checking continuously this blog and I am impressed! Very helpful information :)

    Thanks and best of luck.

Leave a Reply

Your email address will not be published. Required fields are marked *