Delete File to Recycle Bin in C#

In this post we would see how we delete the file to Recycle Bin.

Using the File.Delete() method from System.IO namespace, would delete the file permanently from the system. However we could delete the file which will delete the file to Recycle Bin. To do so, we need to add reference to the Microsoft.VisualBasic assembly.



After you have added the assembly reference to the project, use the following namespace.


Before using the DeleteFile() method, you need to check for file existence. The FileSystem.FileExists() method checks the file existence. In the following example, we are using the DeleteFile() method of FileSystem; where we are providing three parameters to the method. The first one is the file path, the second one provides the dialogs prompt, the third one provides the RecycleOption. Using the following code would delete the files to Recycle Bin silently.


To have dialogs, you need to use the UIOption.AllDialogs enum value.


When you run the above code, the following dialog is prompted.


If you are using above code for displaying dialog, then you should also consider using the fourth parameter to the method. Which is UICancelOption; it has two values such as DoNothing and ThrowException. The DoNothing would pass when user cancels the delete operation.


The following code shows that, the ThrowException option is used in UICancelOption.


Running the above code, would provide the exception as expected; when we cancel the delete operation.


Hope this post is useful.

Thanks for reading. Like Method Of Tried in Facebook.