本文介绍了使用System.IO.Compression.FileSystem向现有ZIP文件添加完整目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下示例可在Internet和本网站上作为使用.NET Framework4.5压缩文件的解决方案进行回溯它可以工作,但当存档已经存在时,它会给出一个错误,因为它似乎只能压缩文件夹和创建新的压缩文件:

[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.ZipFileExages],但您可以将文件添加到现有存档,但只能通过单独添加文件,不允许使用文件夹或通配符:

[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()
我已经创建了单独处理文件的脚本,但处理同一归档中的数千个以上的文件需要很长时间,因此我的问题是:有没有办法一次将完整的文件夹添加到现有的压缩存档中?

顺便说一句,我很惊讶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()

推荐答案

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

这篇关于使用System.IO.Compression.FileSystem向现有ZIP文件添加完整目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 01:20