tags:

views:

226

answers:

4
+4  A: 

Use the RemoveDir() procedure instead. Make sure it is not a current directory for your app, or any other too, or it will remain. SysUtils must be used to get the function.

If you need to, delete the contents of the directory first (below). Recursive deleting is possible, and consider the implications of the '.' test if you use directories or files with '.'.

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;
mj2008
removedir() only works on empty folders
Omair Iqbal
I've added code that will delete contents first. You could merge them into one easily.
mj2008
but can we not use deletefile to delete directory somehow i saw this on a german site and author used it to delete a folder
Omair Iqbal
I suspect that the DeleteFile you saw was a custom version which did what this code does. You can do the same - just make sure that your unit is last in the Uses clause.
mj2008
+3  A: 

You can use the shell functions. According to delphi.about.com, this will delete nonempty folders even if they contain subfolders:

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;
Ralph Rickenbach
but is it that deletefile is not for deleting folders or am i using it incorrectly?
Omair Iqbal
+3  A: 

You can use the function SHFileOperation from the Windows API. A reference to it is defined in ShellApi. However, I would recommend looking into the Jedi Code Library. The unit JclFileUtils contains a DeleteDirectory function which is much easier to use; it even has the option to send the deleted directory to the recycle bin.

Lawrence Barsanti
+2  A: 

What you're doing wrong is using DeleteFile to delete something that isn't a file. The documentation advises you:

The documentation doesn't explicitly tell you not to use DeleteFile on directories, but it's implied by those other two instructions.

Rob Kennedy