Search code examples
vb.netuploadftptransferftpwebrequest

Get the ftp upload speed with vb.net


I'm trying to get the upload speed of a ftp stream with vb.net unsuccessfully...

I'm not sure if the maths are ok, I googled for a while trying to find the equation for upload and i found it in some code examples but for download...

Here is my code:

Dim chunksize As Integer = 2048
Dim offset As Long = 0
Dim readBytes As Long = 0

Dim startTime As DateTime
Dim endTime As DateTime

While offset < buffer.Length
    readBytes = fileStream.Read(buffer, 0, chunksize)
    requestStream.Write(buffer, 0, readBytes)
    offset += readBytes

    endTime = DateTime.Now
    Dim duration = endTime - startTime
    Dim inASec As Double = 1000 / duration.Milliseconds
    startTime = DateTime.Now

    RaiseEvent FileSpeed(Math.Round((64 * inASec) / 8, 2).ToString)

    RaiseEvent FileProgress(offset, buffer.Length)
End While

Solution

  • I think that you are going about it slightly incorrectly. I think you would have better luck calculating the overall speed by measuring the total number of bytes that have been transferred and then dividing that by the total number of seconds that have elapsed.

    For example, something roughly like this:

        Dim chunksize As Integer = 2048
        Dim offset As Long = 0
        Dim readBytes As Long = 0
    
        Dim startTime As DateTime
        Dim duration As Double
    
        startTime = DateTime.Now
    
        While offset < Buffer.Length
            readBytes = fileStream.Read(Buffer, 0, chunksize)
            requestStream.Write(Buffer, 0, readBytes)
            offset += readBytes
    
            duration = startTime.Subtract(Date.Now).TotalSeconds
            ' Avoid divide by 0 errors
            If duration = 0 Then
                duration = 1
            End If
    
            RaiseEvent FileSpeed(Math.Round(offset / duration, 2).ToString)
    
            RaiseEvent FileProgress(offset, Buffer.Length)
        End While