System.IO.Compression and ZipFile - extract and ov

2019-06-15 04:16发布

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

2条回答
虎瘦雄心在
2楼-- · 2019-06-15 04:25

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 
查看更多
闹够了就滚
3楼-- · 2019-06-15 04:35

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
查看更多
登录 后发表回答