问题
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.
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.
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)
Since the files go in multiple folders having already existent files I'd avoid manual
IO.File.Delete(..)
回答1:
Use ExtractToFile with overwrite as true to overwrite an existing file that has the same name as the destination file
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
回答2:
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
来源:https://stackoverflow.com/questions/15464740/system-io-compression-and-zipfile-extract-and-overwrite