我正在尝试每周自动下载一次大型 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.
希望你对这个问题有一个解释!