我正在尝试每周自动下载一个大型zip文件。到目前为止,我已经设法检查是否上传了一个新文件,我已准备好开始下载,但我遇到了一些问题。我正在下载的文件超过2.2 GB(Zip),因此它是一个非常大的文件,每次我测试一个新的代码和平时,我需要等待5-10分钟再次下载该文件。我在底部有一个更复杂的代码,首先是一个简单的代码。一旦最后几个字节被传输,两者都会导致相同的错误。
Try
My.Computer.Network.DownloadFile(
"ftp://dmr-ftp-user:dmrpassword@5.44.137.84/ESStatistikListeModtag/ESStatistikListeModtag-20160110-093818.zip",
"C:\ZipDownload\Test.zip")
Catch ex As Exception
MsgBox(ex.Message)
End Try
是的,这是ftp主机的实际登录信息,因此如果您想在发布可能的解决方案之前测试您的代码 - 请随意。一旦文件即将完成下载,我将得到以下异常:
Exception: The underlying connection was closed: An unexpected error occurred on a receive.
我也试过这个在网上找到的稍微复杂的版本:
Private Sub Download(ByVal filePath As String, ByVal fileName As String)
FTPSettings.IP = "5.44.137.84"
FTPSettings.UserID = "dmr-ftp-user"
FTPSettings.Password = "dmrpassword"
Dim reqFTP As FtpWebRequest = Nothing
Dim ftpStream As Stream = Nothing
Try
Dim outputStream As New FileStream(filePath + "\" + fileName, FileMode.Create)
reqFTP = DirectCast(FtpWebRequest.Create(New Uri("ftp://" + FTPSettings.IP + "/" + fileName)), FtpWebRequest)
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile
reqFTP.UseBinary = True
reqFTP.Credentials = New NetworkCredential(FTPSettings.UserID, FTPSettings.Password)
Dim response As FtpWebResponse = DirectCast(reqFTP.GetResponse(), FtpWebResponse)
ftpStream = response.GetResponseStream()
Dim cl As Long = response.ContentLength
Dim bufferSize As Integer = 2048
Dim readCount As Integer
Dim buffer As Byte() = New Byte(bufferSize - 1) {}
Dim size As Int64
readCount = ftpStream.Read(buffer, 0, bufferSize)
While readCount > 0
outputStream.Write(buffer, 0, readCount)
readCount = ftpStream.Read(buffer, 0, bufferSize)
If readCount = bufferSize Then
size += readCount
Label1.Text = size
Label1.Refresh()
End If
End While
ftpStream.Close()
outputStream.Close()
response.Close()
Catch ex As Exception
MsgBox(ex.Message)
If ftpStream IsNot Nothing Then
ftpStream.Close()
ftpStream.Dispose()
End If
Throw New Exception(ex.Message.ToString())
End Try
End Sub
Public NotInheritable Class FTPSettings
Private Sub New()
End Sub
Public Shared Property IP() As String
Get
Return m_IP
End Get
Set(ByVal value As String)
m_IP = value
End Set
End Property
Private Shared m_IP As String
Public Shared Property UserID() As String
Get
Return m_UserID
End Get
Set(ByVal value As String)
m_UserID = value
End Set
End Property
Private Shared m_UserID As String
Public Shared Property Password() As String
Get
Return m_Password
End Get
Set(ByVal value As String)
m_Password = value
End Set
End Property
Private Shared m_Password As String
End Class
End Class
这两个解决方案似乎都运行得很好,我可以跟踪我的测试文件夹上的文件大小增加,直到最后冻结几秒然后返回相同的异常:
Exception: The underlying connection was closed: An unexpected error occurred on a receive.
希望你对这个问题有解释!