I am using the following code located here to upload files
Public Function UploadFile(ByVal oFile As FileInfo) As Boolean
Dim ftpRequest As FtpWebRequest
Dim ftpResponse As FtpWebResponse
Try
ftpRequest = CType(FtpWebRequest.Create(FTPSite + CurrentDirectory + oFile.Name), _
FtpWebRequest)
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile
ftpRequest.Proxy = Nothing
ftpRequest.UseBinary = True
ftpRequest.Credentials = New NetworkCredential(UserName, Password)
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
I would like to extend it, so i can have an upload progress too. The problem is that i do not know from where to start. What is the "logic" of displaying the upload progress?
"Split the file" in predefined parts and upload them or what?
You need to execute the upload request on a background thread to avoid blocking the UI thread. The easiest way to do this is using the BackgroundWorker class. It's designed specifically for situations like this.
Dim backgroundWorker As New System.ComponentModel.BackgroundWorker()
backgroundWorker.WorkerReportsProgress = True
backgroundWorker.WorkerSupportsCancellation = True
AddHandler backgroundWorker.DoWork, AddressOf Me.BackgroundFileDownload
AddHandler backgroundWorker.ProgressChanged, AddressOf Me.ProgressChanged
AddHandler backgroundWorker.RunWorkerCompleted, AddressOf Me.JobCompleted
The events ProgressChanged and RunWorkerCompleted are run on the UI thread, and allow you to update the progress bar accordingly with the current download's status. They'll look something like this:
Protected Sub ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs)
progressBar.Value = e.ProgressPercentage
End Sub
DoWork is called on a background thread, and is where you want to actually call the UploadFile() function you've written. For FtpWebRequest, you're going to want to first get the file's size, then as you upload blocks of data, divide what you've uploaded so far by the file's full size to get a percentage complete. Something like
Worker.ReportProgress(Math.Round((_bytesUploaded / _fileSize) * 100))
Hope this helps.