free web hosting | free website | Web Hosting | Free Website Submission | shopping cart | Coaching Institute | php hosting
affordable web hosting Pets web page hosting web hosting website hosting web hosting service web hosting web host
How to send files to the system Recycle Bin

How to send files to the system Recycle Bin

CFile is a natural selection for file I/O transactions in MFC, such as reading and writing to a file and to alter the file attributes. CFile is equipped with such functions as rename and remove.

When you want to have more advanced options, such as to throw away the files into the system Recycle Bin, or to remove directories, you will find that the CFile file removal function CFile::Remove() actually only can be applied to the specified file and not to a directory, and the function will not send the file to the Recycle Bin. It will erase the applied file entirely out of existence.

If you want to delete directores or send files to Recycle Bin, you can explore this SHFileOperation function. A functional and working piece of code is supplied at the end of this page so feel free to use it in your application.

In fact, the function is not that hard to use. First of all, the file name must be supplied to the function. This part is not too much of a problem for an experienced C user, but can be tricky if not. Multiple files can be specified, and the file names must be separated by a null. And the file name variable must be terminated with double null's.

Then set other options in SHFILEOPSTRUCT structure. Shown in the code below will send files or directories to the system Recycle Bin. Please refer to the manual for more information on other options for the SHFILEOPSTRUCT structure.

Call SHFileOperation and set the argument as the pointer to the SHFILEOPSTRUCT structure. Everything done. In this way, the files or directories deletion is safe and can be undo-able.


void SendFileToRecycleBin(CString fileName)
{
	int len=fileName.GetLength();
	TCHAR* buf=(TCHAR*)malloc(sizeof(TCHAR)*(len+2));
	wcscpy(buf,fileName.GetBuffer());
	buf[len+1]='\0';

	SHFILEOPSTRUCT FileOp;
	FileOp.hwnd = this->GetSafeHwnd();
	FileOp.wFunc = FO_DELETE;
	FileOp.pFrom =buf;
	FileOp.pTo = NULL; 
	FileOp.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT;
	FileOp.fAnyOperationsAborted = FALSE;
	FileOp.hNameMappings = NULL;
	FileOp.lpszProgressTitle = NULL;

	SHFileOperation( &FileOp );
	free(buf);
}


Return to Home Page
Erica Asai
Last Modified: Sun Oct 29 04:42:25 2006