Empty Recycle Bin Using C#

Introduction

When you use Windows you are aware of the Recycle Bin. Whether it is Windows 98 or Windows 8, the Recycle Bin is a prominent icon on your Desktop. So, you must have an issue with a major problem that we all have, emptying the Recycle Bin.

Recycle Bin

So, in this article we will create a Windows Forms form to do that.

Background

To do this we need the system method SHEmptyRecyleBin() that is in Shell32.dll.

SHEmptyRecyleBin() needs three arguments.

So, let's start the code.

Procedure

Step 1

Before we start, add System.Runtime.InteropService to your project.

Then import the Shell32.dll in your class.

Add this:

[DllImport("Shell32.dll")]

static extern int SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath, RecycleFlag dwFlags);

In your Form class.

Step 2

Define an enum for the RecycleBin flags.

enum RecycleFlag : int

{

    SHERB_NOCONFIRMATION = 0x00000001, // No confirmation, when emptying

    SHERB_NOPROGRESSUI = 0x00000001, // No progress tracking window during the emptying of the recycle bin

    SHERB_NOSOUND = 0x00000004 // No sound when the emptying of the recycle bin is complete

}

Keep those words the same, since you are dealing with a System process (Shell32.exe) and you need to follow the rules.

And, those values are in Hexadecimal.

Now, we will use these Hex values in our method call.

Step 3

When the user clicks on the clear button, then the C# runtime calls the system method in Shell32.dll.

SHEmptyRecycleBin(IntPtr.Zero, null, RecycleFlag.SHERB_NOSOUND | RecycleFlag.SHERB_NOCONFIRMATION);

Windows Forms Demo

Windows Form Demo

After clicking on the button, we get a message box of successfully done.

message box

And now, we have an Empty Recycle Bin.

Empty Recycle Bin

Conclusion

You can add a notify icon or put it in the Startup folder so you get it in every startup. There are so many improvements you can make with it. If you encounter any difficulty in the code above then you can refer to the attached solution file.