Delphi XE2 TZipFile:替换zip存档中的文件

前端之家收集整理的这篇文章主要介绍了Delphi XE2 TZipFile:替换zip存档中的文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想用Delphi XE2 / XE3标准System.Zip单元替换zip存档中的文件(= delete old和add new).但是没有替换/删除方法.有没有人知道如何在不需要提取所有文件并将其添加到新存档的情况下实现它?

我有这个代码,但如果它已经存在,它会再次添加“document.txt”:

  1. var
  2. ZipFile: TZipFile;
  3. SS: TStringStream;
  4. const
  5. ZipDocument = 'E:\document.zip';
  6. begin
  7. ZipFile := TZipFile.Create; //Zipfile: TZipFile
  8. SS := TStringStream.Create('hello');
  9. try
  10. if FileExists(ZipDocument) then
  11. ZipFile.Open(ZipDocument,zmReadWrite)
  12. else
  13. ZipFile.Open(ZipDocument,zmWrite);
  14.  
  15. ZipFile.Add(SS,'document.txt');
  16.  
  17. ZipFile.Close;
  18. finally
  19. SS.Free;
  20. ZipFile.Free;
  21. end;
  22. end;

注意:我之前使用过TPAbbrevia(完成了这项工作),但我现在想使用Delphi的Zip单元.所以请不要回答“使用其他图书馆”之类的内容.谢谢.

解决方法

我推荐Abbrevia因为我有偏见:),你已经知道了,它不需要任何黑客攻击.除此之外,这是你的黑客:
  1. type
  2. TZipFileHelper = class helper for TZipFile
  3. procedure Delete(FileName: string);
  4. end;
  5.  
  6. { TZipFileHelper }
  7.  
  8. procedure TZipFileHelper.Delete(FileName: string);
  9. var
  10. i,j: Integer;
  11. StartOffset,EndOffset,Size: UInt32;
  12. Header: TZipHeader;
  13. Buf: TBytes;
  14. begin
  15. i := IndexOf(FileName);
  16. if i <> -1 then begin
  17. // Find extents for existing file in the file stream
  18. StartOffset := Self.FFiles[i].LocalHeaderOffset;
  19. EndOffset := Self.FEndFileData;
  20. for j := 0 to Self.FFiles.Count - 1 do begin
  21. if (Self.FFiles[j].LocalHeaderOffset > StartOffset) and
  22. (Self.FFiles[j].LocalHeaderOffset <= EndOffset) then
  23. EndOffset := Self.FFiles[j].LocalHeaderOffset;
  24. end;
  25. Size := EndOffset - StartOffset;
  26. // Update central directory header data
  27. Self.FFiles.Delete(i);
  28. for j := 0 to Self.FFiles.Count - 1 do begin
  29. Header := Self.FFiles[j];
  30. if Header.LocalHeaderOffset > StartOffset then begin
  31. Header.LocalHeaderOffset := Header.LocalHeaderOffset - Size;
  32. Self.FFiles[j] := Header;
  33. end;
  34. end;
  35. // Remove existing file stream
  36. SetLength(Buf,Self.FEndFileData - EndOffset);
  37. Self.FStream.Position := EndOffset;
  38. if Length(Buf) > 0 then
  39. Self.FStream.Read(Buf[0],Length(Buf));
  40. Self.FStream.Size := StartOffset;
  41. if Length(Buf) > 0 then
  42. Self.FStream.Write(Buf[0],Length(Buf));
  43. Self.FEndFileData := Self.FStream.Position;
  44. end;
  45. end;

用法

  1. ZipFile.Delete('document.txt');
  2. ZipFile.Add(SS,'document.txt');

猜你在找的Delphi相关文章