How to empty Recycle Bin in C#
By FoxLearn 11/10/2024 2:16:07 AM 78
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.
- How to handle nulls with SqlDataReader in C#
- Resolve nullable warnings
- Cannot convert null to type parameter ‘T’
- How to create a custom exception in C#
- How to check if a nullable bool is true in C#
- How to make a file read-only in C#
- How to Get all files in a folder in C#
- How to validate an IP address in C#