Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DeleteFile not working

It seems that somewhere in my code the file i am working with has a hold on it somehow, cause i can't seem to delete it. My CopyFile routine seems to work, but after i am done copying it, i can't seem to delete it.

   FSize:=  GetFileSizeExt(InPath + InFileName);
   if FSize <= 0 then
   begin
    //archive file
    if  AfterAction = 'MOVE' then
    begin
     tmpExt:= ExtractFileExt(InFileName);
     if CopyFile(PChar(InPath + InFileName), PChar(MovePath + '\' + ChangeFileExt(InFileName,'') + '_' + FormatDateTime('mmddyyyy-hhmmss', Now) + tmpExt), True) then
     begin
      if not DeleteFile(pchar(InPath + InFileName)) then
      begin
       ExitCode:= 8;
       raise ECustomException.Create('Invalid After Action. Error Deleting File!');
      end;
     end //if CopyFile
     else //if not DeleteFile
     begin
      ExitCode:= 16;
      raise ECustomException.Create('File Copy Error!');
     end; //else
    end; //if  AfterAction = 'MOVE' then
     ExitCode:= 17;
     raise ECustomException.Create('Error Getting file size OR file size less than or equal to zero!');
   end; //if filesize =0

when I set a break point on the line
if not DeleteFile
it always ends up raising the exception. The InPath & InFileName match that used in the
CopyFile routine

Anyways, i always get the error try to delete the file. Does this have anything to do with File Size? I only copy and delete if file size <= 0

like image 292
IElite Avatar asked Dec 12 '22 14:12

IElite


1 Answers

If you don't know why you fail deleting the file, why not let the operating system tell you? Replace this code:

raise ECustomException.Create('Invalid After Action. Error Deleting File!');

with

RaiseLastOSError

I don't think the problem's related to the code you're showing, so here's a list of things to check:

  • The file is not read-only.
  • The file is not on read-only media.
  • The user running the application has the right to delete the file.
  • The file is not in use.

An other thing I'd do: When the exception about not being able to delete the file is raised, before I hit RUN in the IDE, I'd go to Windows Explorer and try deleting the file myself.

like image 165
Cosmin Prund Avatar answered Dec 28 '22 12:12

Cosmin Prund