Sample code for 30+ languages & platforms
Dart

Get the Byte Count of the Last SFTP Read

See more SFTP Examples

Demonstrates the Chilkat SFtp.LastReadNumBytes method, which returns the number of bytes received by the most recent read for a handle. The only argument is the handle.

Background: SFTP reads may return fewer bytes than requested even before the end of the file, so knowing the actual count is useful for tracking progress and for advancing an explicit offset by the right amount. Both a normal EOF read and a failed read report 0, so pair this with Eof and LastReadFailed to interpret a zero-byte result correctly.

Chilkat Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  // Demonstrates the SFtp.LastReadNumBytes method, which returns the number of bytes received by
  // the most recent read for a handle.  The only argument is the handle.

  final sftp = CkSFtp();

  // Connect, authenticate, and initialize the SFTP subsystem.
  final port = 22;
  try {
    sftp.connect('sftp.example.com', port);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // 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.
  final password = 'mySshPassword';

  try {
    sftp.authenticatePw('mySshLogin', password);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  try {
    sftp.initializeSftp();
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  final String handle;
  try {
    handle = sftp.openFile('subdir/data.txt', 'readOnly', 'openExisting');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  final bd = CkBinData();
  final chunkSize = 4096;
  var reading = true;
  while (reading) {
    sftp.readFileBd(handle, chunkSize, bd);
    if (sftp.lastReadFailed(handle)) {
      print(sftp.lastErrorText);
      return;
    }

    // Report how many bytes the last read actually returned.  A normal EOF read reports 0.
    final lastCount = sftp.lastReadNumBytes(handle);
    print('Last read returned $lastCount bytes.');

    reading = !sftp.eof(handle);
  }

  try {
    sftp.closeHandle(handle);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  print('Total: ${bd.numBytes} bytes.');

  sftp.disconnect();
}