使用FtpWebRequest上传Progressbar

时间:2012-01-25 17:04:05

标签: wpf ftpwebrequest

我有一个程序,当文件放在表单上时会将文件上传到我们的服务器,以便我们的客户可以轻松地将大文件发送给我们。 我主要使用它,但是我希望有一个进度条,以便用户知道它正在工作,而不是让它只是坐在那里5分钟,而文件在后台安静地上传。

我很乐意让进度条脉冲显示程序正在运行,而不是冻结。如果我能够显示实际状态,那就更好了。

我的代码:

Private Sub Grid1_Drop(sender As System.Object, e As System.Windows.DragEventArgs) Handles Grid1.Drop
    Dim sFileInfo As System.IO.FileInfo
    Dim sStatus As String = ""

    If e.Data.GetDataPresent("FileDrop") Then
        Try
            Dim theFiles() As String = CType(e.Data.GetData("FileDrop", True), String())
            For Each file As String In theFiles
                sFileInfo = New System.IO.FileInfo(file)

                If UploadFile(txtUsername.Text, sFileInfo) Then
                    lstFileList.Items.Add(file & " - Uploaded")
                Else
                    lstFileList.Items.Add(file & " - Upload Failed")
                End If
            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End If
End Sub

Public Function UploadFile(ByVal User As String, ByVal oFile As FileInfo) As Boolean
    Dim ftpRequest As FtpWebRequest
    Dim ftpResponse As FtpWebResponse
    Try
        ftpRequest = CType(FtpWebRequest.Create(Base + User + "/" + oFile.Name), FtpWebRequest)
        ftpRequest.Method = WebRequestMethods.Ftp.UploadFile
        ftpRequest.Proxy = Nothing
        ftpRequest.UseBinary = True
        ftpRequest.Credentials = Cred
        ftpRequest.KeepAlive = KeepAlive
        ftpRequest.EnableSsl = UseSSL
        If UseSSL Then ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf ValidateServerCertificate)
        Dim fileContents(oFile.Length) As Byte
        Using fr As FileStream = oFile.OpenRead
            fr.Read(fileContents, 0, Convert.ToInt32(oFile.Length))
        End Using
        Using writer As Stream = ftpRequest.GetRequestStream
            writer.Write(fileContents, 0, fileContents.Length)
        End Using
        ftpResponse = CType(ftpRequest.GetResponse, FtpWebResponse)
        ftpResponse.Close()
        ftpRequest = Nothing
        Return True
    Catch ex As WebException
        Return False
    End Try
End Function

1 个答案:

答案 0 :(得分:2)

查看后台工作者类。 http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx将释放您的ui,以便您可以添加进度条控件,并在上传文件时对其进行动画处理