4

Hello I am using the CopyFile function in Delphi 5. But the file is not getting copied to destination. I am not able to see error also. What is the best way to know why CopyFile is failing?

if CopyFile(source, dest, false) then
  ShowMessage('Success')
else
  ShowMessage('Error');

I am getting displayed error always. :(

Jerry Dodge
  • 26,858
  • 31
  • 155
  • 327
Nalu
  • 1,107
  • 4
  • 20
  • 43
  • You should be using pchar (CopyFile(pchar(sourcefile), pchar(destfile), false). To check if file copies, use FileExists(destfile).. You can wrap your CopyFile in a try/except and respond to the exception... – John Easley Aug 09 '12 at 19:18
  • 1
    @JohnEasley That's all true, but doesn't help to identify the error code. – Jerry Dodge Aug 09 '12 at 19:21
  • Primary failure modes: 1. Source does not exist 2. Dest path does not exist 3. Dest file read only 4. Permissions error. – David Heffernan Aug 09 '12 at 20:21
  • For example, trying to replace a file which is currently opened (thus locked) – Jerry Dodge Aug 09 '12 at 21:26
  • @JohnEasley: The cast to `PChar` isn't necessary in most cases (like what appears to be shown here). It typically only applies when Delphi can't automatically do the conversion, like when you combine a variable and a constant (eg., `SourcePath + 'SomeFile.txt'`). – Ken White Aug 09 '12 at 21:59
  • @KenWhite Thank you. The CopyFile parameters (in d2010) are PWideChar. Is it bad programming practice to match parameter types? – John Easley Aug 09 '12 at 22:27
  • 3
    @JohnEasley: This question was about D5/7 (pre-Unicode), where the parameters are `PChar` (same as `PAnsiChar`), and `CopyFile` is actually `CopyFileA` under the hood. Doesn't matter, though - in D2010, `string` is Unicode, and Delphi will still auto-convert when possible without the typecast, same as above; in D2010, `CopyFile` is actually `CopyFileW` for the wide string version. The auto-conversion Delphi does is similar to the way it allows you to drop the `^` operator when accessing class instances (which are pointers) or records like `TPoint`, so you can use `Form1.` instead of `Form1^.` – Ken White Aug 09 '12 at 22:32

1 Answers1

15

If the function fails you can get extended error information, calling the GetLastError method or use the RaiseLastOSError method.

Check this sample

  try
    If copyFile(source , dest,false) then
     ShowMessage('Success')
    else
     RaiseLastOSError;
  except  on E: Exception do
     showMessage(Format('Error executing copyFile %s',[E.Message]));
  end;
RRUZ
  • 134,889
  • 20
  • 356
  • 483