tags:

views:

2248

answers:

3

What are the Win32 APIs to use to programically delete files and folders?

Edit

DeleteFile and RemoveDirectory are what I was looking for. However, for this project I ended up using SHFileOperation. I found the sample code at CodeGuru helpful.

+7  A: 

I think you want DeleteFile and RemoveDirectory

itsmatt
+7  A: 

I believe DeleteFile does not send the file to the Recycle Bin. Also RemoveDirectory removes only empty dirs. SHFileOperation would give you the most control over what and how to delete and would show the standard Windows UI dialog boxes (e.g. "Preparing to delete etc.) if needed.

liggett78
+6  A: 

There are two ways to approach this. One is through the File Services (using commands such as DeleteFile and RemoveDirectory) and the other is through the Windows Shell (using SHFileOperation). The latter is recommended if you want to delete non-empty directories or if you want explorer style feedback (progress dialogs with flying files, for example). The quickest way of doing this is to create a SHFILEOPSTRUCT, initialise it and call SHFileOperation, thus:

void silently_remove_directory(LPCTSTR dir) // Fully qualified name of the directory being deleted, without trailing backslash
{
    SHFILEOPSTRUCT file_op = {
        NULL,
        FO_DELETE,
        dir,
        "",
        FOF_NOCONFIRMATION |
        FOF_NOERRORUI |
        FOF_SILENT,
        false,
        0,
        "" };
    SHFileOperation(&file_op);
}

This silently deletes the entire directory. You can add feedback and prompts by varying the SHFILEOPSTRUCT initialisation - do read up on it.

hatcat