Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Win32 API function to use to delete a folder?

Tags:

winapi

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.

like image 306
Slapout Avatar asked Sep 06 '25 03:09

Slapout


1 Answers

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.

like image 175
hatcat Avatar answered Sep 07 '25 23:09

hatcat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!