Delphi wait until a file copy process is complete
Asked Answered
L

1

8

I have a thread that uses ReadDirectoryChangesW to notify me when a file is added or deleted in a folder.

For each new image, I open the file and create a thumbnail of the image. It would seem however that I receive the notification before the file is completely copied to the destination folder, in which case I only get a partial thumbnail. (Files are copied from remote locations onto a central server and the network can get slow in peak times.)

I do check if the file is in use, but this does not seem to work with image files.

HFileRes := CreateFile(pchar(Filename), GENERIC_READ or GENERIC_WRITE, 0, nil,   OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0) ;
Result := (HFileRes = INVALID_HANDLE_VALUE);
if (not Result) then
  CloseHandle(HFileRes) ;

My question is this: Is there a way to detect when a file is completely copied or do I just wait until the file size or last modification time has not changed since the last time I checked?

Lindeman answered 30/6, 2011 at 15:38 Comment(0)
V
4

To be sure if file transfer is finished check first if you can get exclusive access.

  FileHandle := FileOpen(FileName, fmOpenRead or fmShareExclusive);
  if FileHandle > 0 then
    {valid file handle}
Valuer answered 30/6, 2011 at 17:11 Comment(4)
"If the return value is 0 or greater, the function was successful and the value is the file handle of the opened file."Lew
Thank you. Simple and effective.Lindeman
@GJ, that implies false positive, should be >= 0Lew
FileHandle number 0 is reserved for system. Actualy the best way is to call GetLastError to get right info about file status.Valuer

© 2022 - 2024 — McMap. All rights reserved.