How to compress a directory with the built in .net compression classes?

前端 未结 6 866
囚心锁ツ
囚心锁ツ 2021-01-15 19:15

Using the System.IO.Compression namespaces classes GZIPStream and DeflateStream I successfully can compress and decompress individual files. However, if I pass a directoryna

6条回答
  •  猫巷女王i
    2021-01-15 19:31

    This compresses .\in contents to .\out.zip with Powershell and System.IO.Packaging.ZipPackage following the example here

    $zipArchive = $pwd.path + "\out.zip"
    [System.Reflection.Assembly]::Load("WindowsBase,Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
    $ZipPackage=[System.IO.Packaging.ZipPackage]::Open($zipArchive, [System.IO.FileMode]"OpenOrCreate", [System.IO.FileAccess]"ReadWrite")
    $in = gci .\in | select -expand fullName
    [array]$files = $in -replace "C:","" -replace "\\","/"
    ForEach ($file In $files) {
       $partName=New-Object System.Uri($file, [System.UriKind]"Relative")
       $part=$ZipPackage.CreatePart($partName, "application/zip", [System.IO.Packaging.CompressionOption]"Maximum")
       $bytes=[System.IO.File]::ReadAllBytes($file)
       $stream=$part.GetStream()
       $stream.Write($bytes, 0, $bytes.Length)
       $stream.Close()
                                                        }
    $ZipPackage.Close()
    

提交回复
热议问题