开发者

Getting windows ‘ShFileOperation’ API to recursively delete files in Delphi

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


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. It should recurse automatically unless you ask it not to.

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;


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜