Thread - exemplo de como copiar arquivo dentro de uma thread |
Top Previous Next |
|
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. |