Sample code for 30+ languages & platforms
Xojo Plugin

Get the Byte Count of the Last SFTP Read

See more SFTP Examples

Demonstrates the Chilkat SFtp.LastReadNumBytes method, which returns the number of bytes received by the most recent read for a handle. The only argument is the handle.

Background: SFTP reads may return fewer bytes than requested even before the end of the file, so knowing the actual count is useful for tracking progress and for advancing an explicit offset by the right amount. Both a normal EOF read and a failed read report 0, so pair this with Eof and LastReadFailed to interpret a zero-byte result correctly.

Chilkat Xojo Plugin Downloads

Xojo Plugin
Dim success As Boolean
success = False

//  Demonstrates the SFtp.LastReadNumBytes method, which returns the number of bytes received by
//  the most recent read for a handle.  The only argument is the handle.

Dim sftp As New Chilkat.SFtp

//  Connect, authenticate, and initialize the SFTP subsystem.
Dim port As Int32
port = 22
success = sftp.Connect("sftp.example.com",port)
If (success = False) Then
    System.DebugLog(sftp.LastErrorText)
    Return
End If

//  Normally you would not hard-code the password in source.  You should instead obtain it
//  from an interactive prompt, environment variable, or a secrets vault.
Dim password As String
password = "mySshPassword"

success = sftp.AuthenticatePw("mySshLogin",password)
If (success = False) Then
    System.DebugLog(sftp.LastErrorText)
    Return
End If

success = sftp.InitializeSftp()
If (success = False) Then
    System.DebugLog(sftp.LastErrorText)
    Return
End If

Dim handle As String
handle = sftp.OpenFile("subdir/data.txt","readOnly","openExisting")
If (sftp.LastMethodSuccess = False) Then
    System.DebugLog(sftp.LastErrorText)
    Return
End If

Dim bd As New Chilkat.BinData
Dim chunkSize As Int32
chunkSize = 4096
Dim reading As Boolean
reading = True
While reading
    success = sftp.ReadFileBd(handle,chunkSize,bd)
    If (sftp.LastReadFailed(handle)) Then
        System.DebugLog(sftp.LastErrorText)
        Return
    End If

    //  Report how many bytes the last read actually returned.  A normal EOF read reports 0.
    Dim lastCount As Int32
    lastCount = sftp.LastReadNumBytes(handle)
    System.DebugLog("Last read returned " + Str(lastCount) + " bytes.")

    reading = Not sftp.Eof(handle)
Wend

success = sftp.CloseHandle(handle)
If (success = False) Then
    System.DebugLog(sftp.LastErrorText)
    Return
End If

System.DebugLog("Total: " + Str(bd.NumBytes) + " bytes.")

sftp.Disconnect