如何将 zip 文件提取到目录并覆盖?

How to extract a zip file to directory and overwrite?

我制作了一个小程序,可以从我的网站下载一个 .zip 文件,然后将其安装到特定目录中。除非已经存在同名文件,否则它工作正常,然后我收到错误消息。这是我的代码。

If Form1.CheckBox1.Checked = True Then
    Label4.Text = "Downloading Test File!"
    wc.DownloadFileAsync(New Uri("http://www.example.com/TestFile.zip"), Directory + "\TestFile.zip")
    While wc.IsBusy = True
        Application.DoEvents()
    End While
    ListBox1.Items.Add("Test File")
End If

'Install
If Form1.CheckBox1.Checked = True Then
    ZipFile.ExtractToDirectory(Directory + "\TestFile.zip", Directory_Select.TextBox1.Text)
    ListBox2.Items.Add("Test File")
End If

例如,如果 "TestFile.zip" 中的文件与安装位置同名,则会出现以下错误:

The file 'filePath` already exists.

解压没有完成,因为已经存在同名文件。预先删除文件不是一个好的解决方案,因为会有多个同名文件。

如何边解压边替换?

还有一种方法可以暂停程序直到文件完成提取,因为有些文件很大并且需要一些时间才能提取出来。

在此先感谢您的帮助,我是新手,仍在学习中。感谢您的帮助。

虽然 ExtractToDirectory 方法默认不支持覆盖文件,但 ExtractToFile method has an overload 需要第二个 boolean 变量,允许您覆盖正在提取的文件。您可以做的是遍历存档中的文件并使用 ExtractToFile(filePath, True).

一个一个地提取它们

我创建了一个扩展方法,它就是这样做的,并且已经使用了一段时间。希望你觉得它有用!

将以下模块添加到您的项目中:

Module ZipArchiveExtensions

    <System.Runtime.CompilerServices.Extension>
    Public Sub ExtractToDirectory(archive As ZipArchive,
                                  destinationDirPath As String, overwrite As Boolean)
        If Not overwrite Then
            ' Use the original method.
            archive.ExtractToDirectory(destinationDirPath)
            Exit Sub
        End If

        For Each entry As ZipArchiveEntry In archive.Entries
            Dim fullPath As String = Path.Combine(destinationDirPath, entry.FullName)

            ' If it's a directory, it doesn't have a "Name".
            If String.IsNullOrEmpty(entry.Name) Then
                Directory.CreateDirectory(Path.GetDirectoryName(fullPath))
            Else
                entry.ExtractToFile(fullPath, True)
            End If
        Next entry
    End Sub

End Module

用法:

Using archive = ZipFile.OpenRead(archiveFilePath)
    archive.ExtractToDirectory(destPath, True)
End Using

旁注:不要连接字符串以形成其各个部分的路径;请改用 Path.Combine()