PowerBuilder
PowerBuilder
Check Whether the Last SFTP Read Failed
See more SFTP Examples
Demonstrates the Chilkat SFtp.LastReadFailed method, which returns whether the most recent read for a handle failed. The only argument is the handle. A normal end-of-file is not a failure.
Background: A chunked read loop needs to tell three outcomes apart: more data, a clean end-of-file, and an actual error such as a dropped connection or a revoked handle.
LastReadFailed isolates the error case — it is false on a normal EOF read (which succeeds with zero bytes) and true for an empty, malformed, or already-closed handle — so the loop can stop cleanly on EOF but bail out with an error message on a genuine failure.Chilkat PowerBuilder Downloads
integer li_rc
integer li_Success
oleobject loo_Sftp
integer li_Port
string ls_Password
string ls_Handle
integer li_Reading
integer li_ChunkSize
oleobject loo_Bd
li_Success = 0
// Demonstrates the SFtp.LastReadFailed method, which returns whether the most recent read for a
// handle failed. The only argument is the handle. A normal end-of-file is NOT a failure.
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/data.txt","readOnly","openExisting")
if loo_Sftp.LastMethodSuccess = 0 then
Write-Debug loo_Sftp.LastErrorText
destroy loo_Sftp
return
end if
li_Reading = 1
li_ChunkSize = 4096
loo_Bd = create oleobject
li_rc = loo_Bd.ConnectToNewObject("Chilkat.BinData")
do while li_Reading
li_Success = loo_Sftp.ReadFileBd(ls_Handle,li_ChunkSize,loo_Bd)
// Distinguish an actual read failure from a normal EOF. On EOF the read succeeds, returns
// zero bytes, and LastReadFailed is 0.
if loo_Sftp.LastReadFailed(ls_Handle) then
Write-Debug "Read failed: " + 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 with no read failures."
loo_Sftp.Disconnect()
destroy loo_Sftp
destroy loo_Bd