Mega Code Archive

 
Categories / Delphi / Files
 

How to check, if two files are equal

Title: How to check, if two files are equal {1.} function Are2FilesEqual(const File1, File2: TFileName): Boolean; var ms1, ms2: TMemoryStream; begin Result := False; ms1 := TMemoryStream.Create; try ms1.LoadFromFile(File1); ms2 := TMemoryStream.Create; try ms2.LoadFromFile(File2); if ms1.Size = ms2.Size then Result := CompareMem(ms1.Memory, ms2.memory, ms1.Size); finally ms2.Free; end; finally ms1.Free; end end; procedure TForm1.Button1Click(Sender: TObject); begin if Opendialog1.Execute then if Opendialog2.Execute then if Are2FilesEqual(Opendialog1.FileName, Opendialog2.FileName) then ShowMessage('Files are equal.'); end; {********************************************} {2.} function FilesAreEqual(const File1, File2: TFileName): Boolean; const BlockSize = 65536; var fs1, fs2: TFileStream; L1, L2: Integer; B1, B2: array[1..BlockSize] of Byte; begin Result := False; fs1 := TFileStream.Create(File1, fmOpenRead or fmShareDenyWrite); try fs2 := TFileStream.Create(File2, fmOpenRead or fmShareDenyWrite); try if fs1.Size = fs2.Size then begin while fs1.Position .Size do begin L1 := fs1.Read(B1[1], BlockSize); L2 := fs2.Read(B2[1], BlockSize); if L1 L2 then begin Exit; end; if not CompareMem(@B1[1], @B2[1], L1) then Exit; end; Result := True; end; finally fs2.Free; end; finally fs1.Free; end; end;