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

Posted 朝闻道

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了复制文件时,如何显示进度条(使用BlockRead函数读取数据,并插入application.ProcessMessages)相关的知识,希望对你有一定的参考价值。

procedure mycopyfile(sourcef,targetf:string;i:integer);
var
       FromF,ToF:file;
       NumRead,NumWritten:Integer;
       Buf:array[1..2048] of Char;
       n:integer;
begin
         AssignFile(FromF,sourcef);
         Reset(FromF,    1); {    Record    size    =    1    }
         AssignFile(ToF,targetf); {    Open    output    file    }
         Rewrite(ToF,    1); {    Record    size    =    1    }
         n:=0;   
         repeat
                   BlockRead(FromF,    Buf,    SizeOf(Buf),    NumRead);
                   form1.ProgressBar1.Position:=sizeof(buf)*n*100    div    FileSize(FromF)*i div 4;
                   application.ProcessMessages;
                   //显示进度
                   BlockWrite(ToF,    Buf,    NumRead,    NumWritten);
                   inc(n);
           until    (NumRead    =    0)    or    (NumWritten    <>    NumRead);
           form1.ProgressBar1.Position:=100;
           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 := 0;
  setStream.Position := 0;
  BufSize := num;
  block := BufSize div 100;
  GetMem(buf, BufSize);
  ProgressBar1.Max := 100;
  ProgressBar1.Min := 0;
  ProgressBar1.Position := 0;
  while num <> 0 do
  begin
    Application.ProcessMessages;
    n := block;
    if n > num then n := num;
    getStream.ReadBuffer(buf^, n);
    setStream.WriteBuffer(buf^, n);
    ProgressBar1.Position := Trunc((1 - num / BufSize) * 100);
    Dec(num, n);
  end;
  FreeMem(buf, BufSize);
  getStream.Free;
  setStream.Free;
  ShowMessage(复制完毕);
  ProgressBar1.Position := 0;
end;
end.

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

以上是关于复制文件时,如何显示进度条(使用BlockRead函数读取数据,并插入application.ProcessMessages)的主要内容,如果未能解决你的问题,请参考以下文章

进度条和文件复制问题?

在进度条上显示文件复制状态

如何定位文件中的指定的一个位置(delphi)?

progressbar怎么显示复制进度

vb.net 如何对文件夹实现复制,并显示进度条,每复制一个文件还在richtextbox1中显示出来!

在将文件从捆绑包复制到文档路径时显示进度条[重复]