2

On the page (RemoveDirectory() - function) they say : "The path of the directory to be removed. This path must specify an empty directory, and the calling process must have delete access to the directory."

My question is : How do I delete an non-empty directory using this function ? Is that posible ? Any help will be apreciate !

genpfault
  • 51,148
  • 11
  • 85
  • 139
Zero Memory DLL
  • 149
  • 2
  • 6
  • 1
    Possible duplicate of [Why am I having problems recursively deleting directories?](http://stackoverflow.com/questions/1468774/why-am-i-having-problems-recursively-deleting-directories) – Richard Critten Apr 03 '17 at 14:07
  • 2
    Possible duplicate of [What is the Win32 API function to use to delete a folder?](http://stackoverflow.com/questions/213392/what-is-the-win32-api-function-to-use-to-delete-a-folder) – Phil Brubaker Apr 03 '17 at 14:13
  • 1
    You quoted the documentation saying "the path must specify an empty directory". I'm curious as to why you now think there is a way to make it so that "the path needn't specify an empty directory". – Lightness Races in Orbit Apr 03 '17 at 14:32
  • @BoundaryImposition I wanted to be sure. And if I couldn't do that using RemoveFolder(), I'v asked for other methods. I thank Jerry Coffin for his answer. He guided me on the right path. – Zero Memory DLL Apr 03 '17 at 17:57

1 Answers1

4

The short answer is that you don't.

If you need to remove a non-empty directory, you do a depth-first traversal of the directory structure. As you traverse an individual directory, you erase all the files it contains. If it contains any sub-directories, you traverse into them, deleting their contents then deleting the (now empty) directory. Lather, rinse, repeat.

Alternatively, use SHFileOperation or (if you're feeling truly masochistic) IFileOperation, to handle the heavy lifting for you (but beware that the latter is a COM interface, so getting it to handle the heavy lifting will be at least twice as much work as doing the job yourself).

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • Oh.. Okay, I will give it a try. Thank you for the answer. – Zero Memory DLL Apr 03 '17 at 14:19
  • 1
    Note that use of `SHFileOperation()` is specifically stated in the [`RemoveDirectory()` documentation](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365488.aspx): "*To recursively delete the files in a directory, use the `SHFileOperation` function.*" – Remy Lebeau Apr 03 '17 at 18:11
  • I ended up using `RemoveDirectoryW()` and existing utility functions to do recursive remove because `SHFileOperationW()` is ancient and [problematic](https://ofekshilon.com/2009/12/25/deleting-folders/). – Peter L Nov 06 '19 at 01:07