Tuesday, 4 December 2012

How to copy files in Delphi

Here are 2 methods for copying files in Delphi.

Method 1:

procedure FileCopy(const SourceFilename, TargetFilename: string);
var   
 s, t: TFileStream;
begin
    s := TFileStream.Create(SourceFilename, fmOpenRead);
    try
      t := TFileStream.Create(TargetFilename, fmOpenwrite or fmCreate);
      try
        t.CopyFrom(s, s.size);
      finally
        t.free;
      end;
    finally
        s.free;
    end;
end;

Method 2:

procedure FileCopy(const SourceFilename, TargetFilename: string);
var   
  fromF,toF: file;
  numRead, numWritten: word;
  buf: array[1..2048] of char;
begin

  AssignFile(fromF, SourceFilename);
  Reset(fromF, 1);
  AssignFile(toF, TargetFilename);
  Rewrite(ToF, 1); 
  repeat 
    BlockRead(fromF, buf, SizeOF(Buf), numRead);
    BlockWrite(toF, buf, numRead, numWritten);
  until (numRead = 0) or (numWritten <> numRead);
  CloseFile(fromF);
  CloseFile(toF); 
end;

No comments:

Post a Comment