4

If possible, I want to be able to check whether or not the recycle bin is empty, with minimal hassle (importing dlls, importing anything, creating entire new class to hold recycle bin functionality etc...)

I already have the code below that I found online to empty the recycle bin so it seems natural to suspect that I should be able to extend this to check if it needs emptying first, perhaps.. another function within Shell32.dll.

enum BinFlags : uint
{
    SHERB_NOCONFIRMATION = 0x00000001,
    SHERB_NOPROGRESSUI = 0x00000002,
    SHERB_NOSOUND = 0x00000004
}


[DllImport("Shell32.dll", CharSet = CharSet.Unicode)]
static extern uint SHEmptyRecycleBin(IntPtr hwnd, string rootPath,
                                         BinFlags flags);

/* snip, bunch of code... */

SHEmptyRecycleBin(IntPtr.Zero, null, 0);
Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
MrVimes
  • 3,212
  • 10
  • 39
  • 57
  • Alas, to my knowledge you cannot lock the recycle bin, so even if you check if it needs emptying before actually emptying it, *some other process can sneak in and drop a file right after you check and before you empty.* Therefore, that file will not be deleted. – Frédéric Hamidi Jan 04 '14 at 21:39
  • I'm willing to accept that risk. Basically if my code checks the recycle bin - finds it to be empty - then acts accordingly, and something gets added to the recycle bin immediately after.. I am ok with this. – MrVimes Jan 04 '14 at 21:39

2 Answers2

4

You can add reference to the C:\Windows\System32\Shell32.dll and use the following snippet:

Shell shell = new Shell();
Folder recycleBin = shell.NameSpace(10);
int itemsCount = recycleBin.Items().Count;

Taken from here.

Community
  • 1
  • 1
Yurii
  • 4,811
  • 7
  • 32
  • 41
  • Thankyou. This works and is straightforward. I will be able to understand what's going on when I look at my code in the future. – MrVimes Jan 04 '14 at 22:34
1

It's poor documentation, but you might want SHQueryRecycleBin EDIT: Slightly better documentation over at MSDN.

[DllImport("shell32.dll")]
static extern int SHQueryRecycleBin(string pszRootPath, ref SHQUERYRBINFO
   pSHQueryRBInfo);

[StructLayout(LayoutKind.Sequential, Pack=4)]
public struct SHQUERYRBINFO
{
    public int  cbSize;
    public long i64Size;
    public long i64NumItems;
}

It looks like you make the call and it fills the object and if you look at i64NumItems and it is 0 then the recycle bin is empty.

public static int GetCount()
{
    SHQUERYRBINFO sqrbi = new SHQUERYRBINFO();
    sqrbi.cbSize = Marshal.SizeOf(typeof(SHQUERYRBINFO));
    int hresult = SHQueryRecycleBin(string.Empty, ref sqrbi);
    return (int)sqrbi.i64NumItems;
}
Corey Ogburn
  • 24,072
  • 31
  • 113
  • 188