How to delete files to the Recycle Bin using c# and managed code


  • Hi,

    Desperately trying to delete files to the recycle bin using c# managed code.


    What I tried already:


    a) System.IO.File.Delete(filename) unfortunately has no option like *use recycle bin* or anything else

    b) System.Environment.GetFolder(Environment.SpecialFolder ... lists approx. 20 foldertypes but not the recycle bin


    Is there any way to do that using managed code?

    Why isn't the recycle bin not listed in the SpecialFolders enum?


    Thanks in advance for any hint.



    Monday, December 03, 2007 2:52 PM


All replies

  •  Dennis Stone - MSFT wrote:

    See this post:



    Thanks Dennis,

    although it's not managed code it helps ;-)


    Just one remark: There is an important thing when using the function SHFileOperation which is not mentioned in the post of the above link. I discovered that on some files I was getting the error 1026. After a while of searching in other forums I was lucky to find the solution. Obviously this function needs to have a "\0" after the filename to run properly (see line 4 in 'DeleteFilesToRecycleBin'). Here is my c# code which now runs perfectly. Thanks again to all contributors.


    Code Block

    class Win32ApiFunctions


    [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)]

    static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);

    const int FO_DELETE = 3;

    const int FOF_ALLOWUNDO = 0x40;

    const int FOF_NOCONFIRMATION = 0x10; //Don't prompt the user.;



    private static void DeleteFilesToRecycleBin(string filename)



    shf.wFunc = FO_DELETE;


    shf.pFrom = filename + "\0";


    int result = SHFileOperation(ref shf);


    if (result != 0)

    Console.WriteLine(string.Format("error: {0} while moving file {1} to recycle bin", result, filename));




Tuesday, December 04, 2007 5:46 AM