System.IO.Compression和ZipFile - 提取和覆盖

use*_*647 15 .net vb.net compression zip system.io.compression

我正在使用标准的VB.NET库来提取和压缩文件.它的工作原理也是如此,但是当我必须提取文件时,问题就出现了.

我用的代码

进口:

Imports System.IO.Compression
Run Code Online (Sandbox Code Playgroud)

方法我崩溃时调用

ZipFile.ExtractToDirectory(archivedir, BaseDir)
Run Code Online (Sandbox Code Playgroud)

archivedir和BaseDir也被设置,实际上如果没有要覆盖的文件它就可以工作.这个问题恰恰出现了.

如何在不使用第三方库的情况下覆盖提取中的文件?

(注意我使用的是参考System.IO.Compression和System.IO.Compression.Filesystem)

由于文件放在已存在文件的多个文件夹中,我将避免手动

IO.File.Delete(..)
Run Code Online (Sandbox Code Playgroud)

vol*_*ody 15

overwractToFile与overwrite as 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 
Run Code Online (Sandbox Code Playgroud)


小智 11

我发现以下实现完全解决了上述问题,运行没有错误,并成功覆盖现有文件并根据需要创建目录.

        ' 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
Run Code Online (Sandbox Code Playgroud)