delphifilesize

Delphi Determine filesize in real time


Is it possible in Delphi to determine the size of a file as it is being copied? I get a notification when a file is first copied to a folder, but need to wait until the copy is complete before I can process the file.

I've used JclFileUtils.GetSizeOfFile(Filename) but that gives me the 'expected' file size, not the current filesize.


Solution

  • Prompted by the first answer I decided to give up on trying to determine when a file copy has completed. Instead I found that using TFileStream gave me a reliable indication whether a file is in use or not.

    function IsFileInUse(Filename: string; var ResultMessage: string): boolean;
    var
      Stream: TFileStream;
    begin
      Result := True;
      ResultMessage := '';
      try
        Stream := TFileStream.Create(Filename, fmOpenRead or fmShareDenyWrite);
        try
          Result := False;
        finally
          FreeAndNil(Stream);
        end;
    
      Except on E: Exception do
        ResultMessage := 'IsFileInUse: ' + E.Message
      end;
    end;
    

    In this way I can keep on checking until the file is not in use anymore before attempting to process it.