gpt4 book ai didi

vb.net - 使用VB.net通过拖放将多个文件上传到FTP服务器时出现问题

转载 作者:行者123 更新时间:2023-12-03 09:00:28 25 4
gpt4 key购买 nike

我试图通过拖放将多个文件添加到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

最佳答案

由于每次加载文件时都会调用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

关于vb.net - 使用VB.net通过拖放将多个文件上传到FTP服务器时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6882483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com