Currently I'm using the following function
file.Delete();
But how can I use this function to send a file to the recycle bin instead of just deleting it outright?
Currently I'm using the following function
file.Delete();
But how can I use this function to send a file to the recycle bin instead of just deleting it outright?
Use FileSystem.DeleteFile and specify the right RecycleOption.
While this will work with UI Interactive Apps, it will not work with non UI interactive apps like a Windows Service app.
Unfortunately you need to resort to the Win32 API to remove a file to the Recycle Bin. Try the following code, based on this post. It makes use of the generic
SHFileOperation
function for file system operations via the Windows Shell.Define the following (in a utilities class is probably best).
And to use it to delete a file, sending it to the Recycle Bin, you want something like:
NOTE: This also does not work with non UI Interactive apps like Windows Services
This wrapper can provide you needed functionality:
From MSDN:
Add a reference to Microsoft.VisualBasic assembly. The needed class is found in this library.
Add this using statement to the top of the file
using Microsoft.VisualBasic.FileIO
;Use
FileSystem.DeleteFile
to delete a file, it has the option to specify recycle bin or not.Use
FileSystem.DeleteDirectory
to delete a directory with the option to specify to send it to the recycle bin or not.You can DllImport
SHFileOperation
to do this.The following solution is simpler than the other ones:
You can use other functionalities of the recycle bin using this library.
First, don't forget to add the library "Microsoft Shell Controls And Automation" (from the COM menu), to be able to use the
Shell32
namespace. It will be dynamically linked to your project, instead of being compiled along with your program.