2008. július 20., vasárnap

Demo of file copying (TFileStream) in a thread (TThread)


Problem/Question/Abstract:

Demo of file coping (TFileStream) in a thread (TThread). It also resumes copying of files that have been partialy copied.

Answer:

unit copythread;

interface

uses
  Classes, SysUtils;

const
  KB1 = 1024;
  MB1 = 1024 * KB1;
  GB1 = 1024 * MB1;

type
  TCopyFile = class(TThread)
  public
    Percent: Integer;
    Done, ToDo: Integer;
    Start: TDateTime;
    constructor Create(Src, Dest: string);
  private
    { Private declarations }
    IName, OName: string;
  protected
    procedure Execute; override;
  end;

implementation

{ TCopyFile }

constructor TCopyFile.Create(Src, Dest: string);
begin
  IName := Src;
  OName := Dest;
  Percent := 0;
  Start := Now;
  FreeOnTerminate := True;
  inherited Create(True);
end;

procedure TCopyFile.Execute;
var
  fi, fo: TFileStream;
  dod, did: Integer;
  cnt, max: Integer;

begin

  Start := Now;
  try
    { Open existing destination }
    fo := TFileStream.Create(OName, fmOpenReadWrite);
    fo.Position := fo.size;
  except
    { otherwise Create destination }
    fo := TFileStream.Create(OName, fmCreate);
  end;
  try
    { open source }
    fi := TFileStream.Create(IName, fmOpenRead);
    try
      { synchronise dest en src }
      cnt := fo.Position;
      fi.Position := cnt;
      max := fi.Size;
      ToDo := Max - cnt;
      Done := 0;

      { start copying }
      repeat
        dod := MB1; // Block size
        if cnt + dod > max then
          dod := max - cnt;
        if dod > 0 then
          did := fo.CopyFrom(fi, dod);
        cnt := cnt + did;
        Percent := Round(Cnt / Max * 100);

        Done := Done + did;
        ToDo := Max;
      until (dod = 0) or (Terminated);

    finally
      fi.free;
    end;
  finally
    fo.free;
  end;
end;

end.

Nincsenek megjegyzések:

Megjegyzés küldése