Please enable JavaScript to view this site.

Codolex

Navigation: Activities > Zipping

Add to zipfile

Scroll Prev Top Next More

Add to zipfile can be used to add files or directories to an open zip file.

Uses System.Zip.TZipFile.Add

 

AddToZipFile

Activity properties

 

begin

var ArchiveName := '';

var ZipFile1 := ZipFile;

 

for var ContentPath in StringArray do

begin

  var IsDirectory := TDirectory.Exists(ContentPath);

  if IsDirectory then

  begin

    var FolderInArchive := TPath.GetFileName(ContentPath) + '/';

     ZipFile1.Add(TBytes(nil), FolderInArchive, zcDeflate);

     

    var Files := TStringList.Create;

     Files.AddStrings(TDirectory.GetFiles(ContentPath));

     

    var FileItem: string;

    for FileItem in Files do

    begin

       ArchiveName := TPath.Combine(FolderInArchive, TPath.GetFileName(FileItem));

       ZipFile1.Add(FileItem, ArchiveName, zcDeflate);

    end;

     

    var SubFolders := TStringList.Create;

     SubFolders.AddStrings(TDirectory.GetDirectories(ContentPath, '*.*', TSearchOption.soAllDirectories));

     

    for var SubFolderItem in SubFolders do

    begin

       Files.Clear;

       Files.AddStrings(TDirectory.GetFiles(SubFolderItem));

       

      var SubFolderName := TPath.GetFileName(SubFolderItem) + '/';

      var SubFolderArchiveName := TPath.Combine(FolderInArchive, SubFolderName);

       ZipFile1.Add(TBytes(nil), SubFolderArchiveName, zcDeflate);

       

      for FileItem in Files do

      begin

         ArchiveName := TPath.Combine(SubFolderArchiveName, TPath.GetFileName(FileItem));

         ZipFile1.Add(FileItem, ArchiveName, zcDeflate);

      end;

    end;

  end

  else

  begin

     ArchiveName := TPath.GetFileName(ContentPath);

     ZipFile1.Add(ContentPath, ArchiveName, zcDeflate);

  end;

end;

end;

Resulting Code

 

The provided zipfile can be a string with the path, or a variable of the TZipFile type.

If a existing TZipFile variable is provided, the File must be Opened before adding.

 

'Files/content to add' can be a string or an array of strings, the paths can be folders or files.

 

The compression method is Deflate by default.

More about compression methods can be found in the embarcadero wikki: System.Zip.TZipCompression

 

When adding folders, there are 2 options to concider.

If only the option to 'add all files from folder' is checked, only the files directly in the folder are added to the zip.

To include folders and files in those folders, the option 'Include subfolders' are also checked.

 

To prevent errors in the zip file, always Close the zipfile after adding to the zip.

 

 

© by GDK Software