2015-05-15 21 views
0

因此,我有一個簡單的ftp傳輸函數,它可以在緩衝區上發送大塊文件到我的服務器。我嘗試上傳一個300MB的文件,並且完全沒有問題,但在函數完成發送1.5GB文件的每個單個字節後,該函數在writer.close()上崩潰。VB.NET中的FtpWebRequest的GetRequestStream的writer.close()錯誤

然後,我收到以下錯誤: 「底層連接已關閉:接收時發生意外錯誤。」

Public Function upload(ByRef fullpath As String, ByRef filename As String) As Boolean 
    If filename <> "" Then 
     Try 
      Dim clsRequest As FtpWebRequest = DirectCast(WebRequest.Create("ftp://myserver" & filename), FtpWebRequest) 
      clsRequest.Credentials = New NetworkCredential(user, password) 
      clsRequest.Method = WebRequestMethods.Ftp.UploadFile 
      clsRequest.KeepAlive = True 
      clsRequest.Timeout = -1 
      clsRequest.UsePassive = True 


      Dim FileInfo As FileInfo = New FileInfo(fullpath) 
      Dim bfile() As Byte = New Byte((FileInfo.Length) - 1) {} 
      clsRequest.ContentLength = FileInfo.Length 


      Dim bytesRead As Integer 
      Dim buffer(4096) As Byte 
      Using reader As FileStream = FileInfo.OpenRead 
       Using writer As Stream = clsRequest.GetRequestStream 
        Do 
         bytesRead = reader.Read(buffer, 0, buffer.Length) 
         If bytesRead > 0 Then 
          writer.Write(buffer, 0, bytesRead) 
         End If 
        Loop While bytesRead > 0 
        writer.Flush() 
        ''crashes here >>>>>>> 
        writer.Close() 
       End Using 
       reader.Flush() 
       reader.Close() 

      End Using 

      Return True 


     Catch ex As Exception 
      Return False 
     End Try 

    End If 


End Function 

編輯:

所以,我發現了一個「解決方案」,它包括所有字節傳送完成後做一個.abort()在連接上的。它完美的工作,我沒有看到任何缺點,但是我發現這樣做很sl kind。會有什麼真正的解決辦法嗎?

回答

1

here

This problem occurs when the server or another network device unexpectedly closes an existing Transmission Control Protocol (TCP) connection. This problem may occur when a time-out value on the server or on the network device is set too low. ... The problem can also occur if the server resets the connection unexpectedly, such as if an unhandled exception crashes the server process. Analyze the server logs to see if this may be the issue.

有提出多種解決方案。

此外,Using塊處理關閉/處置writer(另有一個reader),所以你不需要手動處理它,這是.Close在做什麼。

Stream.Close Method

This method calls Dispose, specifying true to release all resources. You do not have to specifically call the Close method. Instead, ensure that every Stream object is properly disposed. You can declare Stream objects within a using block (or Using block in Visual Basic) to ensure that the stream and all of its resources are disposed, or you can explicitly call the Dispose method.

+0

好點的使用配置,但現在它崩潰代替。 :S,不幸的是我無法控制服務器,因爲它是共享主機。 – Robotometry