Empty Recycle Bin using C#
Introduction
In this blog post, we will show you how to empty recycle bin using C#.
Using Windows API
We can use Windows API to empty recycle bin. In this example, it will suppress confirmation dialogs (SHERB_NOCONFIRMATION
), progress UI (SHERB_NOPROGRESSUI
), and sounds (SHERB_NOSOUND
) during the operation.
using System.Runtime.InteropServices;
namespace ConsoleApp1
{
internal class Program
{
private const int SHERB_NOCONFIRMATION = 0x00000001;
private const int SHERB_NOPROGRESSUI = 0x00000002;
private const int SHERB_NOSOUND = 0x00000004;
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
private static extern int SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath, int dwFlags);
static void Main(string[] args)
{
try
{
int result = SHEmptyRecycleBin(IntPtr.Zero, null, SHERB_NOCONFIRMATION | SHERB_NOPROGRESSUI | SHERB_NOSOUND);
if (result == 0)
{
Console.WriteLine("Recycle bin emptied successfully.");
}
else
{
Console.WriteLine("Failed to empty recycle bin.");
}
}
catch (Exception ex)
{
Console.WriteLine($"Failed to empty recycle bin: {ex.Message}");
}
}
}
}
SHEmptyRecycleBin
function is declared using Platform Invocation Services (P/Invoke
). P/Invoke
allows C# code to call functions in unmanaged Windows libraries.
Conclusion
To empty recycle bin using C#, we can use Windows API. It provides a set of functions and interfaces that allow us to interact with Windows shell such as managing recycle bin. The primary function used in Windows API solution is SHEmptyRecycleBin
.