我正在尝试通过拖放将多个文件添加到FTP服务器,我可以使用try catch块来执行此操作,如果我们正确地提供ftp设置,则上传它们需要1秒,但是当我们提供错误的详细信息时如果我发出特殊消息,我会挂断并且不会给我任何错误消息。
现在我收到错误消息以及我添加的每个文件的成功消息。我不希望这种情况发生。
任何人都可以说我应该在哪里提供成功和失败的消息,以便上传需要几秒钟,如果不能立即给我留言。
在我出错的地方,我感到很困惑。
任何帮助将不胜感激!
这是我的代码:
Private Sub uploadFile(ByVal FTPAddress As String, ByVal filePath As String, ByVal username As String, ByVal password As String) 'Create FTP request
Try
Dim request As FtpWebRequest = DirectCast(FtpWebRequest.Create(FTPAddress & "/" & Path.GetFileName(filePath)), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.UploadFile
request.Credentials = New NetworkCredential(username, password)
request.UsePassive = True
request.UseBinary = True
request.KeepAlive = False
Dim buffer As Byte() = Nothing
'Load the file
Using stream As FileStream = File.OpenRead(filePath)
buffer = New Byte(CInt(stream.Length - 1)) {}
stream.Read(buffer, 0, buffer.Length)
End Using
'Upload file
Using reqStream As Stream = request.GetRequestStream()
reqStream.Write(buffer, 0, buffer.Length)
End Using
MsgBox("Uploaded Successfully", MsgBoxStyle.Information)
Catch
MsgBox("Failed to upload.Please check the ftp settings", MsgBoxStyle.Critical)
End Try
End Sub
以下是拖放代码
Private Sub FlowLayoutPanel1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles FlowLayoutPanel1.DragDrop
Try
Dim Files As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())
For Each FileName As String In Files
Dim Extension As String = Path.GetExtension(FileName).ToLower
If Array.IndexOf(SupportedExtensions, Extension) <> -1 Then
uploadFile(txtFTPAddress.Text, FileName, txtUsername.Text, txtPassword.Text)
End If
Next
Catch
End Try
End Sub
答案 0 :(得分:0)
由于每次加载文件时都会调用uploadFile,因此您可能希望将错误处理代码从此方法移动到dragDrop方法。这样,您将只收到一条消息,说明整个操作成功或失败。您还可以在FtpWebRequest上设置Timeout属性,以便在超过几秒钟时取消上传。
然后uploadFile变为:
Private Sub uploadFile(ByVal FTPAddress As String, ByVal filePath As String, ByVal username As String, ByVal password As String) 'Create FTP request
Dim request as FtpWebRequest = ...
request.Timeout = 5000 ' Set timeout to 5 seconds
'... several lines omitted
'Upload file
Using reqStream As Stream = request.GetRequestStream()
reqStream.Write(buffer, 0, buffer.Length)
End Using
End Sub
然后,您可以将错误处理代码移动到处理拖放的方法中:
Private Sub FlowLayoutPanel1_DragDrop(ByVal sender As Object, ByVal e As
System.Windows.Forms.DragEventArgs) Handles FlowLayoutPanel1.DragDrop
Try
' ... several lines omitted
Next
MsgBox("Uploaded Successfully", MsgBoxStyle.Information)
Catch
MsgBox("Failed to upload.Please check the ftp settings", MsgBoxStyle.Critical)
End Try
End Sub