Code sample for empty Recycle Bin in C#


following is the code sample for deleting all contents of recycle bin in C#.

Following Code sample requires one Button control named ‘btnRecycleBin’ on windows form.

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
 
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        enum RecycleFlags : uint
        {
            SHRB_NOCONFIRMATION = 0x00000001,
            SHRB_NOPROGRESSUI = 0x00000002,
            SHRB_NOSOUND = 0x00000004
        }
        [DllImport("Shell32.dll", CharSet = CharSet.Unicode)]
        static extern uint SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath, RecycleFlags dwFlags);
        private void btnRecycleBin_Click(object sender, EventArgs e)
        {
            DialogResult result;
            result = MessageBox.Show("Are you sure to delete all items in recycle bin", "Empty Recycle bin", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                try
                {
                    uint IsSuccess = SHEmptyRecycleBin(IntPtr.Zero, null, RecycleFlags.SHRB_NOCONFIRMATION);
                    MessageBox.Show("Empty the RecycleBin successsfully", "Empty the RecycleBin", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Empty the RecycleBin failed" + ex.Message, "Empty the RecycleBin", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    Application.Exit();
                }
            }
        }
    }
}