Do not delete a folder using the deletefile command



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

      

code>

i get os error 5: access denied when i use the same code to delete a file, say wwj.txt works fine, but doesn't work for folders, what am i doing wrong?

+2


source to share


4 answers


Use the RemoveDir () procedure instead. Make sure this is not the current directory for your application, or whatever, or it will remain. You must use SysUtils to get the function.

If you need, first delete the directory contents (below). Recursive deletion is possible, and consider the consequences of "." if you are using 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;

      

+5


source


You can use shell functions. According to delphi.about.com , this will delete non-empty folders, even if they contain sub-folders:



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


source


You can use SHFileOperation function from Windows API. It is referenced in ShellApi. However, I would recommend taking a look at the Jedi Code Library . The JclFileUtils unit contains the DeleteDirectory function, which is much easier to use; it even has the ability to send the remote directory to the trash can.

+3


source


What you are doing wrong, use DeleteFile

to delete something that is not a file. The documentation tells you:

The documentation doesn't explicitly state what you don't use DeleteFile

in directories, but it is implied by these two other instructions.

+2


source







All Articles