我想通过附加文件恢复下载,问题是它使文件变大,例如文件A大小为98000kb,当程序下载文件A时,互联网问题或用户中止下载和下载停在2000kb。然后用户继续进行恢复下载,恢复下载,但文件A大小已变为100000 kb。有没有办法解决这个问题?这是我的代码:
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim url As String = e.Argument
'Creating the request and getting the response
Dim strFileName
Dim a As String
Dim b() As String
files = url.Split(CChar(","))
For Each a In files
b = a.Split("/")
strFileName = b(b.Length - 1)
Me.whereToSave = "C:\Temp\" & strFileName
Next
Dim sDestinationPath As String = me.whereToSave 'file destination
Dim iFileSize As Long = 0
Dim iBufferSize As Integer = 1024
iBufferSize *= 1000
Dim iExistLen As Long = 0
Dim saveFileStream As System.IO.FileStream = Nothing
Dim hwRq As System.Net.HttpWebRequest
Dim hwRes As System.Net.HttpWebResponse
hwRq = DirectCast(System.Net.HttpWebRequest.Create(url), System.Net.HttpWebRequest)
hwRq.AddRange(CInt(iExistLen))
Dim smRespStream As System.IO.Stream
hwRes = DirectCast(hwRq.GetResponse(), System.Net.HttpWebResponse)
smRespStream = hwRes.GetResponseStream()
iFileSize = hwRes.ContentLength
If System.IO.File.Exists(sDestinationPath) Then
Dim fINfo As New System.IO.FileInfo(sDestinationPath)
iExistLen = fINfo.Length
End If
If iExistLen = iFileSize Then
MsgBox("exists")
saveFileStream = New System.IO.FileStream(sDestinationPath, System.IO.FileMode.Open, IO.FileAccess.Write, System.IO.FileShare.Read)
ElseIf iExistLen > 0 And iExistLen <= iFileSize Then
MsgBox("Append")
saveFileStream = New System.IO.FileStream(sDestinationPath, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite)
Else
MsgBox("Create")
saveFileStream = New System.IO.FileStream(sDestinationPath, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite)
End If
Dim iByteSize As Integer
Dim downBuffer As Byte() = New Byte(iBufferSize - 1) {}
Dim safedelegate As New ChangeTextsSafe(AddressOf ChangeTexts)
iByteSize = (smRespStream.Read(downBuffer, 0, downBuffer.Length))
While (iByteSize > 0)
saveFileStream.Write(downBuffer, 0, iByteSize)
iByteSize = (smRespStream.Read(downBuffer, 0, downBuffer.Length))
End While
答案 0 :(得分:1)
在检查文件是否已存在并设置其长度之前,您正在设置hwRq.AddRange(CInt(iExistLen))
。
移动此
If System.IO.File.Exists(sDestinationPath) Then
Dim fINfo As New System.IO.FileInfo(sDestinationPath)
iExistLen = fINfo.Length
End If
高于hwRq.AddRange(CInt(iExistLen))