代码之家  ›  专栏  ›  技术社区  ›  Omair Iqbal

无法使用deletefile命令删除文件夹

  •  2
  • Omair Iqbal  · 技术社区  · 16 年前

    procedure TForm1.Button1Click(Sender: TObject);
    begin
      if not deletefile('c:\test') then
      raiselastoserror
    end;
    

    4 回复  |  直到 16 年前
        1
  •  5
  •   mj2008    16 年前

    请改用RemoveDir()过程。确保它不是你的应用程序的当前目录,也不是任何其他目录,否则它将保留。必须使用SysUtils来获取函数。

    如果需要,请先删除目录中的内容(如下)。递归删除是可能的,并考虑“”的含义。'测试是否将目录或文件与'一起使用。'.

    procedure DeleteFiles( szDBDirectory : string );
    var
        szFile : string;
        SearchRec: TSearchRec;
        szSearchPath : string;
        nResult : integer;
    begin
        szSearchPath := szDBDirectory;
        nResult := FindFirst(szSearchPath + '\*.*', faAnyFile, SearchRec);
        try
            while 0 = nResult do
            begin
                if('.' <> SearchRec.Name[1]) then
                begin
                    szFile := szSearchPath + '\' + SearchRec.Name;
    {$IFDEF DEBUG_DELETE}
                    CodeSite.Send('Deleting "' + szFile + '"');
    {$ENDIF}
                    FileSetAttr(szFile, 0);
                    DeleteFile(szFile);
                end;
    
                nResult := FindNext(SearchRec);
            end;
        finally
            FindClose(SearchRec);
        end;
    end;
    
        2
  •  3
  •   Ralph M. Rickenbach    16 年前

    您可以使用shell函数。根据 delphi.about.com ,这将删除非空文件夹,即使它们包含子文件夹:

    uses ShellAPI;
    Function DelTree(DirName : string): Boolean;
    var
      SHFileOpStruct : TSHFileOpStruct;
      DirBuf : array [0..255] of char;
    begin
      try
       Fillchar(SHFileOpStruct,Sizeof(SHFileOpStruct),0) ;
       FillChar(DirBuf, Sizeof(DirBuf), 0 ) ;
       StrPCopy(DirBuf, DirName) ;
       with SHFileOpStruct do begin
        Wnd := 0;
        pFrom := @DirBuf;
        wFunc := FO_DELETE;
        fFlags := FOF_ALLOWUNDO;
        fFlags := fFlags or FOF_NOCONFIRMATION;
        fFlags := fFlags or FOF_SILENT;
       end; 
        Result := (SHFileOperation(SHFileOpStruct) = 0) ;
       except
        Result := False;
      end;
    end;
    
        3
  •  3
  •   Lawrence Barsanti    16 年前

    您可以使用Windows API中的函数SHFileOperation。ShellApi中定义了对它的引用。但是,我建议您研究一下 Jedi Code Library JclFileUtils单元包含一个更易于使用的DeleteDirectory函数;它甚至可以选择将删除的目录发送到回收站。

        4
  •  2
  •   Rob Kennedy    16 年前

    你做错的是使用 DeleteFile 删除非文件内容。 The documentation

    文档没有明确告诉你不要使用 删除文件 在目录上,但其他两条指令暗示了这一点。