Copy file with a Progress bar  

Send By: Radikal (Q3 Team)
Web : http://www.q3.nu
Email: radikal@q3.nu
Date: 28/09/99

Tip accessed 636 times

 


It sometimes interests to indicate the progress of copy of a file.
If we use a function of high level like CopyFile, we will simplify ourselves a lot the life, but we won't be able to use our ProgressBar...
The solution that I propose is the following one:


  • Open the Source file and to create the Target file
  • Read a block of data of the Source file
  • Update the ProgressBar position
  • Save the read block in the target file

    And repeat the process until you have read and save the complete file.

    The example:
    Notice: I have not put any confirmation of errors, that leaves it to you, you already know, test if the Source file exists, to give failure if there is not space in the disk to save the target file, or to check if the target file already exists.

  • Put a ProgressBar (PB1) in your form
  • Put a TButton and put this code in their OnClick event:


     procedure TForm1.Button1Click(Sender: TObject);
     var
        Origen,
        Destino  :file of byte;
        Buffer   :array[0..4096] of char;
        Leidos   :integer;
        Longitud :longint;
     begin
       {Abrimos fichero Origen y Destino}
       AssignFile(Origen,'c:\kk\uno.exe');
       reset(Origen);
       AssignFile(Destino,'c:\kk\dos.exe');
       rewrite(Destino);
       {Hallamos la longitud del fichero a copiar}
       Longitud:=FileSize(Origen);
       {Actualizamos limites de la ProgressBar}
       PB1.Max:=Longitud;
       PB1.Min:=0;
       while Longitud >0 do
       begin
         BlockRead(Origen,Buffer[0],SizeOf(Buffer),Leidos);
         Longitud:=Longitud-Leidos;
         BlockWrite(Destino,Buffer[0],Leidos);
         PB1.Position:=PB1.Position+Leidos;
       end;
       CloseFile(Origen);
       CloseFile(Destino);
     end;
    



    The example uses a buffer of 2048 bytes. When bigger is the buffer more speed he will give you the routine.
    Good, in fact, the good yield would have it if you equal the size from the buffer to the size of the clusters of the disk... (or multiples of it) but don't worry, neither it is so critical the gain of speed, whenever you don't lower the size of the buffer a lot.