2014-07-21 64 views
0

我想通過追加文件恢復下載,問題是它使文件變得更大,例如文件大小爲98000kb,當程序下載文件A,互聯網問題或用戶中止下載並在2000kb停止下載。然後用戶繼續下載恢復下載,但文件大小已變爲100000 kb。有沒有辦法解決這個問題?這裏是我的代碼:繼續下載與stream.addrange

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 

回答

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))

+0

很抱歉這麼晚纔回復的定義。你的代碼有效!謝謝! – plokuun

+0

很高興我能幫到你 – user3036342