If we delete a file or folder using C# code, it will be deleted from the system permanently. Yesterday, I was searching for a solution, which would help me to delete a file to recycle bin. There is no direct API* available in .NET which could help me to achieve this. Later, I found an option using
SHFileOperation will be used to Copy, Move, Rename, or Delete a file system object. And here is the implementation which helped to delete file or folder to Recyclebin.
Using the Code
Given below is the implementation:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)]
public struct SHFILEOPSTRUCT
public IntPtr hwnd;
public int wFunc;
public string pFrom;
public string pTo;
public short fFlags;
public bool fAnyOperationsAborted;
public IntPtr hNameMappings;
public string lpszProgressTitle;
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
public static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);
public const int FO_DELETE = 3;
public const int FOF_ALLOWUNDO = 0x40;
public const int FOF_NOCONFIRMATION = 0x10;
And you can use WIN32 API like this, in the code, we are creating an instance of
wFunc is the value that indicates which operation to perform. The
pFrom is a pointer to one or more source file names. These names should be fully qualified paths to prevent unexpected results.
fFlags control the file operation.
var shf = new SHFILEOPSTRUCT();
shf.wFunc = FO_DELETE; shf.fFlags = FOF_ALLOWUNDO; shf.pFrom = @"c:\myfile.txt" + '\0' + '\0'; SHFileOperation(ref shf);
pFrom parameter can be either file or folder. * This is not 100% true. We can do this by using
Microsoft.VisualBasic namespace. And here is the implementation.
string path = @"c:\myfile.txt";