In this blog post, I’m talking about, how to detect if recycle bin is empty or not. Also the code snippet allow you to get total count of the items there in the recycle bin.

The contents of Recycle bin appears be in a single folder while it remains in one or more than one of your physical hard drives. You can se the percentage of allocation for each drive in the recycle bin property page as we’re seeing below.

image

The snippet mainly using two functions

SHQueryRecycleBin – Retrieves the size of the Recycle Bin and the number of items in it, for a specified drive.

GetLogicalDriveStrings – helps to retrieve the strings that specify valid drives in the system.

Calling GetLogicalDriveStrings with NULL values will return how many characters need to be passed to fill the data. The return string doesn’t include terminating null character and also in the end the function will put additional null character to specify the end of the data. So we’ve to add 2 characters extra to number of characters to be allocated. The retrieved drive names can be used as input for SHQueryRecyleBin function. If you pass NULL it will give total count of the items in the recyle bin. But it’s adviced not use in that way. See teh documentation for more information. See the sample snippet below

#include <windows.h>
#include <shellapi.h>
#include <iostream>

using namespace std;

bool IsRecycleBinEmpty( DWORDLONG& dwCount )
{
	bool bRet = false;

	dwCount = 0;

	DWORD dwSize = GetLogicalDriveStrings(0, NULL);

	// dwSize + 2 null chars
	dwSize += 2;

	LPTSTR pszDrives	= (LPTSTR)malloc((dwSize + 2) * sizeof (TCHAR));

	if( NULL != pszDrives )
	{
		LPTSTR pstr = pszDrives;
		SHQUERYRBINFO stInfo;

		GetLogicalDriveStrings((dwSize) * sizeof (TCHAR),pszDrives);

		while ( _T('') != *pstr )
		{
			ZeroMemory (&stInfo, sizeof (stInfo));
			stInfo.cbSize = sizeof (stInfo);
			HRESULT	hr = SHQueryRecycleBin (pstr, &stInfo);
			if( SUCCEEDED (hr) && stInfo.i64NumItems)
			{
				dwCount += stInfo.i64NumItems;
			}
			pstr += _tcslen(pstr) + sizeof (TCHAR);
		}
		free( pszDrives );
	}
	return dwCount ? true : false;
}

int _tmain(int argc, _TCHAR* argv[])
{
	DWORDLONG dwCount = 0;
	if( IsRecycleBinEmpty( dwCount ))
	{
		cout << "Recycle bin contains " << dwCount << "items";
	}
	else
	{
		cout << "Recyle Bin is empty";
	}

	return 0;
}