复制文件时,如何显示进度条(使用BlockRead函数读取数据,并插入application.ProcessMessages)

时间:2022-03-27 16:30:12
procedure mycopyfile(sourcef,targetf:string;i:integer);
var
FromF,ToF:file;
NumRead,NumWritten:Integer;
Buf:array[..] of Char;
n:integer;
begin
AssignFile(FromF,sourcef);
Reset(FromF, ); { Record size = 1 }
AssignFile(ToF,targetf); { Open output file }
Rewrite(ToF, ); { Record size = 1 }
n:=;
repeat
BlockRead(FromF, Buf, SizeOf(Buf), NumRead);
form1.ProgressBar1.Position:=sizeof(buf)*n* div FileSize(FromF)*i div ;
application.ProcessMessages;
//显示进度
BlockWrite(ToF, Buf, NumRead, NumWritten);
inc(n);
until (NumRead = ) or (NumWritten <> NumRead);
form1.ProgressBar1.Position:=;
CloseFile(FromF);
CloseFile(ToF);
end;

完整代码:

以下例子是关于delphi复制文件,加上进度条的方法的例子的关键代码:
procedure TForm1.Button1Click(Sender: TObject);
const
getPath = 'c:/temp/get.rar';
setPath = 'c:/temp/set.rar';
var
getStream,setStream: TFileStream;
num, n: Integer;
buf: PByte;
BufSize,block: Integer;
begin
if not FileExists(getPath) then
begin
ShowMessage('源文件不存在');
Exit;
end;
getStream := TFileStream.Create(getPath, fmOpenRead or fmShareExclusive);
setStream := TFileStream.Create(setPath, fmCreate);
num := getStream.Size;
setStream.Size := num;
getStream.Position := ;
setStream.Position := ;
BufSize := num;
block := BufSize div ;
GetMem(buf, BufSize);
ProgressBar1.Max := ;
ProgressBar1.Min := ;
ProgressBar1.Position := ;
while num <> do
begin
Application.ProcessMessages;
n := block;
if n > num then n := num;
getStream.ReadBuffer(buf^, n);
setStream.WriteBuffer(buf^, n);
ProgressBar1.Position := Trunc(( - num / BufSize) * );
Dec(num, n);
end;
FreeMem(buf, BufSize);
getStream.Free;
setStream.Free;
ShowMessage('复制完毕');
ProgressBar1.Position := ;
end;
end.

http://blog.csdn.net/shuaihj/article/details/6129551