Копирование файлов
Материал из DRKB
Копирование методом Pascal[править | править код]
type
TCallBack = procedure(Position, Size: Longint); { Для индикации процесса копирования }
procedure FastFileCopy(const InfileName, OutFileName: string; CallBack: TCallBack);
const
BufSize = 3 * 4 * 4096; { 48Kbytes дает прекрасный результат }
type
PBuffer = ^TBuffer;
TBuffer = array [1..BufSize] of Byte;
var
Size : Integer;
Buffer : PBuffer;
infile, outfile : File;
SizeDone,SizeFile: Longint;
begin
if (InFileName <> OutFileName) then
begin
Buffer := Nil;
AssignFile(infile, InFileName);
System.Reset(infile, 1);
try
SizeFile := FileSize(infile);
AssignFile(outfile, OutFileName);
System.Rewrite(outfile, 1);
try
SizeDone := 0; New(Buffer);
repeat
BlockRead(infile, Buffer^, BufSize, Size);
Inc(SizeDone, Size);
CallBack(SizeDone, SizeFile);
BlockWrite(outfile,Buffer^, Size)
until Size < BufSize;
FileSetDate(TFileRec(outfile).Handle,
FileGetDate(TFileRec(infile).Handle));
finally
if Buffer <> Nil then Dispose(Buffer);
System.Close(outfile)
end;
finally
System.Close(infile);
end;
end
else
Raise EInOutError.Create('File cannot be copied into itself');
end;
Копирование методом потока[править | править код]
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);
FileSetDate(T.Handle, FileGetDate(S.Handle));
finally
T.Free;
end;
finally
S.Free;
end;
end;
Копирование методом LZExpand[править | править код]
uses LZExpand;
procedure CopyFile(FromFileName, ToFileName: string);
var
FromFile, ToFile: File;
begin
AssignFile(FromFile, FromFileName);
AssignFile(ToFile, ToFileName);
Reset(FromFile);
try
Rewrite(ToFile);
try
if LZCopy(TFileRec(FromFile).Handle, TFileRec(ToFile).Handle) < 0 then
raise Exception.Create('Error using LZCopy')
finally
CloseFile(ToFile);
end;
finally
CloseFile(FromFile);
end;
end;
Копирование методами Windows[править | править код]
uses ShellApi; // !!! важно
function WindowsCopyFile(FromFile, ToDir: string): Boolean;
var
F: TShFileOpStruct;
begin
F.Wnd := 0;
F.wFunc := FO_COPY;
FromFile := FromFile + #0;
F.pFrom := PChar(FromFile);
ToDir := ToDir + #0;
F.pTo := PChar(ToDir);
F.fFlags := FOF_ALLOWUNDO or FOF_NOCONFIRMATION;
Result := (ShFileOperation(F) = 0);
end;
// пример копирования
procedure TForm1.Button1Click(Sender: TObject);
begin
if not WindowsCopyFile('C:\UTIL\ARJ.EXE', GetCurrentDir) then
ShowMessage('Copy Failed');
end;
Source: http://dmitry9.nm.ru/info/
ID: 03176