Delphi ActiveX
Delphi ActiveX
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 Delphi ActiveX Downloads
var
success: Integer;
sftp: TChilkatSFtp;
port: Integer;
password: WideString;
handle: WideString;
sbContent: TChilkatStringBuilder;
chunkSize: Integer;
reading: Integer;
chunk: WideString;
begin
success := 0;
// 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.
sftp := TChilkatSFtp.Create(Self);
// Connect, authenticate, and initialize the SFTP subsystem.
port := 22;
success := sftp.Connect('sftp.example.com',port);
if (success = 0) then
begin
Memo1.Lines.Add(sftp.LastErrorText);
Exit;
end;
// 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.
password := 'mySshPassword';
success := sftp.AuthenticatePw('mySshLogin',password);
if (success = 0) then
begin
Memo1.Lines.Add(sftp.LastErrorText);
Exit;
end;
success := sftp.InitializeSftp();
if (success = 0) then
begin
Memo1.Lines.Add(sftp.LastErrorText);
Exit;
end;
handle := sftp.OpenFile('subdir/data.txt','readOnly','openExisting');
if (sftp.LastMethodSuccess = 0) then
begin
Memo1.Lines.Add(sftp.LastErrorText);
Exit;
end;
// 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.
sbContent := TChilkatStringBuilder.Create(Self);
chunkSize := 4096;
reading := 1;
while reading do
begin
chunk := sftp.ReadFileText(handle,chunkSize,'utf-8');
if (sftp.LastReadFailed(handle)) then
begin
Memo1.Lines.Add(sftp.LastErrorText);
Exit;
end;
sbContent.Append(chunk);
reading := not sftp.Eof(handle);
end;
success := sftp.CloseHandle(handle);
if (success = 0) then
begin
Memo1.Lines.Add(sftp.LastErrorText);
Exit;
end;
Memo1.Lines.Add(sbContent.GetAsString());
sftp.Disconnect();