【问题标题】:How to extract a zip file to directory and overwrite?如何将 zip 文件提取到目录并覆盖?
【发布时间】:2018-09-08 20:48:12
【问题描述】:

我制作了一个小程序,可以从我的网站下载 .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”中的文件与安装位置同名,它会给我以下错误:

文件“filePath”已经存在。

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

提取时如何替换?

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

提前感谢您帮助我,我是新手,还在学习中。感谢您的帮助。

【问题讨论】:

  • 定义“暂停程序”的含义。这似乎是一个 WinForms 应用程序,因此在提取时,UI 线程无论如何都会被阻止;这就是你所说的“暂停”吗?或者你的意思是相反的(即,在提取时保持程序响应)?
  • because there will be multiple files with the same name.,听起来你有更大的问题。你怎么能拥有一个同名的文件并在同一个目录中多次键入?另一方面,删除DoEvents,它们是代码异味。
  • @Codexer 我认为 OP 的意思是说 “存档中将有多个文件的名称已经存在于目标文件夹中”

标签: vb.net zipfile overwrite


【解决方案1】:

虽然ExtractToDirectory 方法默认不支持覆盖文件,但ExtractToFile 方法有一个overload,它需要第二个布尔 变量,允许您覆盖正在提取的文件.您可以做的是遍历存档中的文件并使用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()

【讨论】:

  • 感谢您的回复。在这里回答你所有的cmets。 @Ahmed Abdelhameed,我暂停程序的意思是:当程序将第一个文件提取到目标位置时,它不会在 / 它完成提取第一个文件之后继续执行代码,然后再移动到下一个文件。我会在几个小时内尝试你的代码。感谢那。 @Coderex。问题是所有 zip 文件都提取到相同的目的地。该软件基本上是通过替换游戏文件来安装游戏插件,这就是为什么它相同并且有许多同名的原因。感谢您的宝贵时间
猜你喜欢
  • 2021-03-02
  • 2018-01-18
  • 1970-01-01
  • 2020-06-17
  • 1970-01-01
  • 1970-01-01
  • 2013-01-27
  • 1970-01-01
  • 2013-12-28
相关资源
最近更新 更多