How to empty Recycle Bin in C#

By FoxLearn 11/10/2024 2:16:07 AM   3
To empty the Recycle Bin in C#, you can use the SHEmptyRecycleBin function from the Windows Shell API.

The .NET Framework does not provide a built-in method to empty the Recycle Bin. However, this task can be accomplished easily by using the Shell Win32 API, which offers functionality to interact with the system's shell, including managing Recycle Bin contents.

To empty the Recycle Bin, you can simply call the `SHEmptyRecycleBin()` function from `shell32.dll`, as demonstrated in the example code. This function allows you to programmatically clear the Recycle Bin by invoking it through Platform Invocation Services (P/Invoke) in C#.

class Program
{
    static void Main(string[] args)
    {
        // Do not show confirm message box
        const int SHERB_NOCONFIRMATION = 0x00000001;         
        // empty Recycle Bin
        SHEmptyRecycleBin(IntPtr.Zero, null, SHERB_NOCONFIRMATION);
    }
 
    [DllImport("shell32.dll")]
    static extern int SHEmptyRecycleBin(IntPtr hWnd, string pszRootPath, uint dwFlags);
}

The third parameter (`SHERB_NOCONFIRMATION`) in the `SHEmptyRecycleBin()` function prevents the confirmation message box from appearing. If you want the confirmation message box to be displayed, simply pass `0` as the third parameter instead.