Creating Compressed (Zipped) Folder using Delphi

前端 未结 9 2200
日久生厌
日久生厌 2021-02-05 18:52

Can I create Windows XP\'s Compressed (Zipped) Folder using Delphi?

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-05 19:17

    The TZipFile.ZipDirectoryContents method did not work for me, so I created my own implementation using TZipFile.add(). I am posting it here if anyone needs it.

    procedure CreateZipOfDirectory(directory: string);
    var
      zip: TZipFile;
      Arr: tarray;
      str: string;
      
      function GetAllFilesInDir(const Dir: string): tarray;
      var
        Search: TSearchRec;
        procedure addAll(arr: tarray; parent: string);
        var
          tmp: string;
        begin
          for tmp in arr do
          begin
            setlength(result, length(result) + 1);
            result[length(result) - 1] := IncludeTrailingBackslash(parent) + tmp;
          end;
        end;
      begin
        setlength(result, 0);
        if FindFirst(IncludeTrailingBackslash(Dir) + '*.*', faAnyFile or faDirectory, Search) = 0 then
          try
            repeat
              if (Search.Attr and faDirectory) = 0 then
              begin
                setlength(result, length(result) + 1);
                result[length(result) - 1] := Search.Name;
              end
              else if (Search.Name <> '..') and (Search.Name <> '.') then
                addAll(GetAllFilesInDir(IncludeTrailingBackslash(Dir) + Search.Name), Search.Name);
            until FindNext(Search) <> 0;
          finally
            FindClose(Search);
          end;
      end;
    
    begin
      Zip := TZipFile.Create;
      try
        Zip.Open('Foo.zip', zmWrite);
        arr := GetAllFilesInDir(directory); // The Delphi TZipFile.ZipDirectoryContents does not work properly, so let's create our own.
        for str in arr do
          zip.Add(directory + str, str); // Add the second parameter to make sure that the file structure is preserved.
      finally
        zip.Free;
      end;
    end;
    

提交回复
热议问题