.net System.IO.Compression 和 ZipFile - 提取和覆盖
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15464740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
System.IO.Compression and ZipFile - extract and overwrite
提问by user1714647
I'm using the standard VB.NET libraries for extracting and compressing files. It works as well but the problem comes when I have to extract and files exist already.
我使用标准的 VB.NET 库来提取和压缩文件。它也可以工作,但是当我必须提取并且文件已经存在时问题就出现了。
Code I use
我使用的代码
Imports:
进口:
Imports System.IO.Compression
Method I call when it crashes
崩溃时调用的方法
ZipFile.ExtractToDirectory(archivedir, BaseDir)
archivedir and BaseDir are set as well, in fact it works if there are no files to overwrite. The problem comes exactly when there are.
archivedir 和 BaseDir 也已设置,实际上,如果没有要覆盖的文件,它就可以工作。问题出现的时候就出现了。
How can I overwrite files in extraction without use thirdy-part libraries?
如何在不使用第三方库的情况下覆盖提取中的文件?
(Note I'm using as Reference System.IO.Compression and System.IO.Compression.Filesystem)
(注意我用作参考 System.IO.Compression 和 System.IO.Compression.Filesystem)
Since the files go in multiple folders having already existent files I'd avoid manual
由于文件位于已存在文件的多个文件夹中,因此我会避免手动
IO.File.Delete(..)
回答by volody
Use ExtractToFilewith overwrite as true to overwrite an existing file that has the same name as the destination file
使用ExtractToFile和 overwrite 为 true 来覆盖与目标文件同名的现有文件
Dim zipPath As String = "c:\example\start.zip"
Dim extractPath As String = "c:\example\extract"
Using archive As ZipArchive = ZipFile.OpenRead(zipPath)
For Each entry As ZipArchiveEntry In archive.Entries
entry.ExtractToFile(Path.Combine(extractPath, entry.FullName), True)
Next
End Using
回答by jamezj
I found the following implementation fully worked to solve the problems described above, ran without errors and successfully overwrote existing files and created directories as needed.
我发现以下实现完全可以解决上述问题,运行没有错误并成功覆盖现有文件并根据需要创建目录。
' Extract the files - v2
Using archive As ZipArchive = ZipFile.OpenRead(fullPath)
For Each entry As ZipArchiveEntry In archive.Entries
Dim entryFullname = Path.Combine(ExtractToPath, entry.FullName)
Dim entryPath = Path.GetDirectoryName(entryFullName)
If (Not (Directory.Exists(entryPath))) Then
Directory.CreateDirectory(entryPath)
End If
Dim entryFn = Path.GetFileName(entryFullname)
If (Not String.IsNullOrEmpty(entryFn)) Then
entry.ExtractToFile(entryFullname, True)
End If
Next
End Using

