我制作了一个程序,从我的网站下载.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”中的文件与Install location同名,则会出现以下错误:
文件'filePath`已存在。
它没有完成提取,因为已经存在具有相同名称的文件。事先删除文件不是一个好的解决方案,因为会有多个具有相同名称的文件。
提取时如何更换?
还有一种方法可以暂停程序直到文件完成提取,因为某些文件很大并且在提取之前需要一些时间。
在此先感谢帮助我,我很新,还在学习。感谢您的帮助。
虽然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()
。