Link to home
Start Free TrialLog in
Avatar of momsoft2
momsoft2

asked on

Why does CopyFile never fail?

I am using CopyFile to make a backup of an important file. It seems that CopyFile always returns true, even if the path is not accessible, or the disk or file are read-only. What system do you recommend to make sure that the file has been copied successfully?
ERROR := Not CopyFile(PChar(ConfigFilename),PChar(ConfigBackup),False);

Open in new window

Avatar of ThievingSix
ThievingSix
Flag of United States of America image

Here's a dirty way to get it done. There are better ways to do it though.
function CopyFile(lpExistingFileName, lpNewFileName: PChar; bFailIfExists: LongBool): LongBool;
var
  FileStreamExisting,
  FileStreamNew : TFileStream;
  Buffer : PChar;
begin
  Result := False;
  If (bFailIfExists) And (FileExists(lpNewFileName)) Then Exit;
  FileStreamExisting := TFileStream.Create(lpExistingFileName,fmOpenRead);
  FileStreamNew := TFileStream.Create(lpNewFileName,fmCreate);
  Try
    If FileStreamNew.CopyFrom(FileStreamExisting,0) = FileStreamExisting.SIze Then
      begin
      Result := True;
    end;
  Finally
    FileStreamExisting.Free;
    FileStreamNew.Free;
  end;
end;

Open in new window

Avatar of momsoft2
momsoft2

ASKER

Thank you very much. This is definitely a step in the right direction.

Your function does indeed fail if the destination is invalid, but then, the original file stays locked and I get errors if I try to access it again.
ASKER CERTIFIED SOLUTION
Avatar of ThievingSix
ThievingSix
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you very much for your help!