Question

I am programing under C++, MFC, windows.

I want to delete a folder into recycle bin. How can I do this?

    CString filePath = directorytoBeDeletePath;
    TCHAR ToBuf[MAX_PATH + 10];
    TCHAR FromBuf[MAX_PATH + 10];
    ZeroMemory(ToBuf, sizeof(ToBuf));
    ZeroMemory(FromBuf, sizeof(FromBuf));

    lstrcpy(FromBuf, filePath);

    SHFILEOPSTRUCT FileOp;
    FileOp.hwnd = NULL
    FileOp.wFunc=FO_DELETE; 
    FileOp.pFrom=FromBuf;
    FileOp.pTo = NULL;
    FileOp.fFlags=FOF_ALLOWUNDO|FOF_NOCONFIRMATION;
    FileOp.hNameMappings=NULL;
    bRet=SHFileOperation(&FileOp);

Any thing wrong with the code above? It always failed.

I found the problem: filePath should be : "c:\abc" not "c:\abc\"

Was it helpful?

Solution

The return value from SHFileOperation is an int, and should specify the error code. What do you get?

OTHER TIPS

i know it is not the right way but if you cant find a solution you can try this..

download file nircmd.exe or another exe that can empty recycle bin.

then you call these functions by system("nircmd.exe emptybin")

You have found a solution that works, however it's only by accident. The actual problem here is that the pFrom parameter is in a special format. According to the MSDN docs for SHFILEOPTS, it stores a list of file paths, each one null-terminated, and an extra null after the last one.

In your case this happens to work because the FromBuf array is longer than the filename and all the entries are initialised to zero. The more general solution is to create a buffer that is long enough for the filename and then add two nul characters after it. Note that Windows filenames can be longer than _MAX_PATH, eg see https://docs.microsoft.com/en-us/windows/desktop/fileio/naming-a-file#maximum-path-length-limitation

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top