使用System.IO.Compression.FileSystem将完整目录添加到现有zip文件

问题描述 投票:1回答:1

以下示例可以在互联网和本网站上进行回溯,作为使用.NET Framework 4.5压缩文件的解决方案。它可以正常工作,但是当存档已经存在时会出现错误,因为它似乎只能压缩文件夹并创建一个新的zip文件:

[Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" )
$src_folder = "D:\stuff"
$destfile = "D:\stuff.zip"
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
$includebasedir = $false
[System.IO.Compression.ZipFile]::CreateFromDirectory($src_folder,$destfile,$compressionLevel, $includebasedir )

我已经尝试过[System.IO.Compression.ZipFileExtensions],但是您可以将文件添加到现有存档中,但只能单独添加它们,不允许使用文件夹或通配符:

[Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" )
$src_folder = "D:\stuff" #also tried D:\stuff\ or D:stuff\*
$destfile = "D:\stuff.zip"
$destfile2=[System.IO.Compression.ZipFile]::Open($destfile, "Update")
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($destfile2,$src_folder,"\",$compressionlevel)
$archiver.Dispose()

我已经创建了单独处理文件的脚本,但是在同一个存档中处理多个文件需要花费很长时间,所以我的问题是:有没有办法将完整的文件夹添加到现有的zip存档中立刻?

顺便说一下,我很惊讶System.IO.Compression.ZipFile的速度有多快。

在看了Noam的回答之后,我意识到它是多么容易,我解决了我的问题:

[Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" )
$src_folder = "D:\stuff\" 
$destfile = "D:\stuff.zip"
$destfile2=[System.IO.Compression.ZipFile]::Open($destfile, "Update")
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
$in = Get-ChildItem $src_folder -Recurse | where {!$_.PsisContainer}| select -expand fullName
[array]$files = $in
ForEach ($file In $files) 
{
        $file2 = $file #whatever you want to call it in the zip
        $null = [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($destfile2,$file,$file2,$compressionlevel)
}
$archiver.Dispose()
powershell powershell-v3.0
1个回答
0
投票

Noam的回答和Jurjen:

[Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" )
$src_folder = "D:\stuff\" 
$destfile = "D:\stuff.zip"
$destfile2=[System.IO.Compression.ZipFile]::Open($destfile, "Update")
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
$in = Get-ChildItem $src_folder -Recurse | where {!$_.PsisContainer}| select -expand fullName
[array]$files = $in
ForEach ($file In $files) 
{
        $file2 = $file #whatever you want to call it in the zip
        $null = [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($destfile2,$file,$file2,$compressionlevel)
}
$archiver.Dispose()
© www.soinside.com 2019 - 2024. All rights reserved.