0

我试图自己做这件事,但遇到了需要帮助的情况。我想使用进度条控件来显示 FTP 文件上传的当前进度。

目前,我正在手动更改进度条控件的值 - 但我不禁认为那里可能有更好或更简单的方法。它现在可以工作,但是进度条在显示基于正在执行的代码部分的进度时是零星的。此外,我试图将整个子程序放入一个单独的线程中,但注意到当我这样做时,进度条直到代码结束才会显示 - 然后它会短暂闪烁并再次隐藏。

这是我到目前为止所做的,任何帮助将不胜感激:

Public Sub uploadAuthorization()

    ProgressBar1.Show()
    Dim fileName As String = Path.GetFileName(TextBoxFilePath.Text)
    Dim ftpFolder As String = "authorizations"

    Try
        'Create FTP Request
        Me.Cursor = Cursors.WaitCursor
        Dim myRequest As FtpWebRequest = DirectCast(WebRequest.Create(ftpServer + "/" + ftpFolder + "/" + fileName), FtpWebRequest)
        ProgressBar1.Value = 20

        'Update properties
        myRequest.Credentials = New NetworkCredential(ftpUsername, ftpPassword)
        myRequest.Method = WebRequestMethods.Ftp.UploadFile
        ProgressBar1.Value = ProgressBar1.Value + 20

        'Read the file
        Dim myFile As Byte() = File.ReadAllBytes(TextBoxFilePath.Text)
        ProgressBar1.Value = ProgressBar1.Value + 20

        'Upload the file
        Dim myStream As Stream = myRequest.GetRequestStream()
        myStream.Write(myFile, 0, myFile.Length)
        ProgressBar1.Value = ProgressBar1.Value + 20

        'Cleanup
        myStream.Close()
        myStream.Dispose()
        ProgressBar1.Value = ProgressBar1.Value + 20

    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Information)
    End Try
    Me.Cursor = Cursors.Arrow
End Sub
4

1 回答 1

0

再一次问好,

因此,根据 Andrew Morton 的建议阅读,这就是我想出的解决方案,它就像一个魅力。唯一的问题是,WebClient 类不支持 FtpWebRequest 类提供的 UploadFileWithUniqueName 方法。我真的很喜欢这个——因为它让我有机会使用随机文件名,但我想这是一个公平的权衡,让进度条正常工作。

所以这是解决方案:


Private WithEvents myFtpUploadWebClient As New WebClient

Private Sub ButtonChooseFile_Click(sender As System.Object, e As System.EventArgs) Handles ButtonChooseFile.Click

    If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
        OpenFileDialog1.Title = "Please choose the Authorization File"
        TextBoxFilePath.Text = OpenFileDialog1.FileName
        ProgressBar1.Show()
        Me.Cursor = Cursors.WaitCursor

        Dim myUri As New Uri(ftpServer & OpenFileDialog1.SafeFileName)
        myFtpUploadWebClient.Credentials = New System.Net.NetworkCredential(ftpUsername, ftpPassword)
        myFtpUploadWebClient.UploadFileAsync(myUri, OpenFileDialog1.FileName)
    End If

End Sub

Private Sub myFtpUploadWebClient_UploadFileCompleted(sender As Object, e As System.Net.UploadFileCompletedEventArgs) Handles myFtpUploadWebClient.UploadFileCompleted

    If e.Error IsNot Nothing Then
        MessageBox.Show(e.Error.Message)
    Else
        Me.Cursor = Cursors.Default
        MessageBox.Show("Authorization Form Uploaded Successfully!")
    End If
End Sub

Private Sub myFtpUploadWebClient_UploadProgressChanged(sender As Object, e As System.Net.UploadProgressChangedEventArgs) Handles myFtpUploadWebClient.UploadProgressChanged
    ProgressBar1.Value = e.ProgressPercentage
End Sub
于 2013-03-04T03:27:50.667 回答