添加一个完整的目录与System.IO.Compression.FileSystem现有的zip文件

2019-08-16 22:33发布

下面的例子是在互联网上,这个网站上的sollution压缩使用.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有多快,出色的。

看着诺姆的回答后,我意识到它是多么容易,我解决我的问题是这样的:

[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()

Answer 1:

诺姆的回答和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()


文章来源: Adding a complete directory to an existing zip file with System.IO.Compression.FileSystem