tags:

views:

359

answers:

2

Hi

I am using the following code to delete a large number of files

function FastDelete(const fromDir: string): Boolean;
var
  fos: TSHFileOpStruct;
begin
  ZeroMemory(@fos, SizeOf(fos));
  with fos do
  begin
    wFunc := FO_DELETE;
    fFlags := FOF_FILESONLY or
              FOF_NOCONFIRMATION or
              FOF_NO_CONNECTED_ELEMENTS or
              FOF_NOERRORUI or
              FOF_NO_UI;
    pFrom := PChar(fromDir+'\*.*' + #0);
  end;
  Result := (0 = ShFileOperation(fos));
end;

How do I get it to recursively delete all the files in the path?

MSDN documentation

EDIT

The problem is the FOF_FILESONLY flag After removing it files are recursively deleted

+4  A: 

From the MSDN documentation:

FOF_NORECURSION:

Only perform the operation in the local directory. Don't operate recursively into subdirectories, which is the default behavior.

Looks like that's your answer right there.

EDIT: Looks like there's a problem with your flags. You need to or them together, not add them together. Since FOF_NO_UI already includes FOF_NOERRORUI, adding it again can change the value, and you might be accidentally adding some things together that add up to FOF_NORECURSION. It should look like this:

    fFlags := FOF_FILESONLY or
              FOF_NOCONFIRMATION or
              FOF_NO_CONNECTED_ELEMENTS or
              FOF_NOERRORUI or
              FOF_NO_UI;
Mason Wheeler
Hi Mason - I am not using FOF_NORECURSION how should I change my code to make it recursively delete the files in the subdirectories ?
Charles Faiga
It should do it recursively by default. Check my edit.
Mason Wheeler
Also, not really sure if the '\*.*' mask is necessary if you are deleting the entire directory. Passing the function the directory itself should be enough
EagleOfToledo
Eagle, it depends on whether you want to delete the directory or just its contents.
Rob Kennedy
Adding a all the flags gives an answer of $2A96 and FOF_NORECURSION = $1000 Thus FOF_NORECURSION has not been enabled
Charles Faiga
Adding or ORing bitmapped flags leads to the same result. OR is often called "logical sum".
ldsandon
Not when one of the flags overlaps another, as is the case here.
Mason Wheeler
@Rob Kennedy - Roger that, its just that as I understand it, and as @Mason Wheeler suggests, when you specify the "all" mask "*.*" it will delete all the files, but not the sub-directories, which is what he needs (I think).
EagleOfToledo
+1  A: 

Do you have to keep the directory also? If not you could just pass

pFrom := PChar(fromDir+#0);

Another option is to build a list of #0-delimited file-paths, and pass that with an extra #0, from msdn:

Although this member is declared as a null-terminated string, it is used as a buffer to hold multiple file names. Each file name must be terminated by a single NULL character. An additional NULL character must be appended to the end of the final name to indicate the end of pFrom.

Stijn Sanders