Sample code for 30+ languages & platforms
Xojo Plugin

Detect End-of-File on a Remote SFTP File

See more SFTP Examples

Demonstrates the Chilkat SFtp.Eof method, which returns whether the most recent read for a handle received the SFTP end-of-file status. The only argument is the handle. This example reads until Eof is true.

Background: The timing here is worth understanding: reading exactly through the final byte does not immediately set EOF. The next read succeeds, returns zero bytes, sets the status to SSH_FX_EOF, and only then does Eof report true. That is why the loop tests Eof after each read rather than assuming a short read means the end — a short read can also just be the server returning less than requested.

Chilkat Xojo Plugin Downloads

Xojo Plugin
Dim success As Boolean
success = False

//  Demonstrates the SFtp.Eof method, which returns whether the most recent read for a handle
//  received the SFTP end-of-file status.  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

//  Read until Eof reports the end of the file.  Note that reading exactly through the final byte
//  does not set EOF; the next read returns zero bytes and then Eof becomes true.
Dim sbContent As New Chilkat.StringBuilder
Dim chunkSize As Int32
chunkSize = 4096
Dim reading As Boolean
reading = True
While reading
    Dim chunk As String
    chunk = sftp.ReadFileText(handle,chunkSize,"utf-8")
    If (sftp.LastReadFailed(handle)) Then
        System.DebugLog(sftp.LastErrorText)
        Return
    End If

    success = sbContent.Append(chunk)
    reading = Not sftp.Eof(handle)
Wend

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

System.DebugLog(sbContent.GetAsString())

sftp.Disconnect