Xojo Plugin
Xojo Plugin
Read Bytes from a Remote SFTP File (BinData)
See more SFTP Examples
Demonstrates the Chilkat SFtp.ReadFileBd method, which reads up to a number of bytes from the current position of an open handle and appends them to a BinData. The arguments are the handle, the maximum number of bytes, and the BinData. This example reads in chunks until end-of-file.
Background: For binary files, reading into a
BinData preserves the bytes exactly, unlike a text read that decodes through a charset. Because it appends, the chunked read loop accumulates the whole file in the BinData; each pass reads up to the chunk size and the loop repeats until Eof. Fewer bytes than requested can come back near the end of the file, which is normal.Chilkat Xojo Plugin Downloads
Dim success As Boolean
success = False
// Demonstrates the SFtp.ReadFileBd method, which reads up to a number of bytes from the current
// position of an open handle and appends them to a BinData. The 1st argument is the handle, the
// 2nd is the maximum number of bytes, and the 3rd is the BinData.
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/image.png","readOnly","openExisting")
If (sftp.LastMethodSuccess = False) Then
System.DebugLog(sftp.LastErrorText)
Return
End If
// Read the file in chunks until end-of-file, accumulating the bytes in a BinData.
Dim bd As New Chilkat.BinData
Dim chunkSize As Int32
chunkSize = 8192
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
reading = Not sftp.Eof(handle)
Wend
success = sftp.CloseHandle(handle)
If (success = False) Then
System.DebugLog(sftp.LastErrorText)
Return
End If
System.DebugLog("Read " + Str(bd.NumBytes) + " bytes.")
sftp.Disconnect