PowerBuilder
PowerBuilder
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 PowerBuilder Downloads
integer li_rc
integer li_Success
oleobject loo_Sftp
integer li_Port
string ls_Password
string ls_Handle
oleobject loo_Bd
integer li_ChunkSize
integer li_Reading
li_Success = 0
// 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.
loo_Sftp = create oleobject
li_rc = loo_Sftp.ConnectToNewObject("Chilkat.SFtp")
if li_rc < 0 then
destroy loo_Sftp
MessageBox("Error","Connecting to COM object failed")
return
end if
// Connect, authenticate, and initialize the SFTP subsystem.
li_Port = 22
li_Success = loo_Sftp.Connect("sftp.example.com",li_Port)
if li_Success = 0 then
Write-Debug loo_Sftp.LastErrorText
destroy loo_Sftp
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.
ls_Password = "mySshPassword"
li_Success = loo_Sftp.AuthenticatePw("mySshLogin",ls_Password)
if li_Success = 0 then
Write-Debug loo_Sftp.LastErrorText
destroy loo_Sftp
return
end if
li_Success = loo_Sftp.InitializeSftp()
if li_Success = 0 then
Write-Debug loo_Sftp.LastErrorText
destroy loo_Sftp
return
end if
ls_Handle = loo_Sftp.OpenFile("subdir/image.png","readOnly","openExisting")
if loo_Sftp.LastMethodSuccess = 0 then
Write-Debug loo_Sftp.LastErrorText
destroy loo_Sftp
return
end if
// Read the file in chunks until end-of-file, accumulating the bytes in a BinData.
loo_Bd = create oleobject
li_rc = loo_Bd.ConnectToNewObject("Chilkat.BinData")
li_ChunkSize = 8192
li_Reading = 1
do while li_Reading
li_Success = loo_Sftp.ReadFileBd(ls_Handle,li_ChunkSize,loo_Bd)
if loo_Sftp.LastReadFailed(ls_Handle) then
Write-Debug loo_Sftp.LastErrorText
destroy loo_Sftp
destroy loo_Bd
return
end if
li_Reading = not loo_Sftp.Eof(ls_Handle)
loop
li_Success = loo_Sftp.CloseHandle(ls_Handle)
if li_Success = 0 then
Write-Debug loo_Sftp.LastErrorText
destroy loo_Sftp
destroy loo_Bd
return
end if
Write-Debug "Read " + string(loo_Bd.NumBytes) + " bytes."
loo_Sftp.Disconnect()
destroy loo_Sftp
destroy loo_Bd