Sample code for 30+ languages & platforms
Dart

SFTP Read Text File to String

See more SFTP Examples

Demonstrates how to download a text file from an SSH server directly into a string variable.

Chilkat Dart Downloads

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

void main() {
  // This example assumes the Chilkat API to have been previously unlocked.
  // See Global Unlock Sample for sample code.

  final sftp = CkSFtp();

  // Set some timeouts, in milliseconds:
  sftp.connectTimeoutMs = 5000;
  sftp.idleTimeoutMs = 15000;

  // Connect to the SSH server.  
  // The standard SSH port = 22
  // The hostname may be a hostname or IP address.
  final hostname = 'sftp.example.com';
  final port = 22;
  try {
    sftp.connect(hostname, port);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Authenticate with the SSH server.  Chilkat SFTP supports
  // both password-based authenication as well as public-key
  // authentication.  This example uses password authenication.
  try {
    sftp.authenticatePw('myLogin', 'myPassword');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // After authenticating, the SFTP subsystem must be initialized:
  try {
    sftp.initializeSftp();
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Open a file on the server:
  var handle = '';
  try {
    handle = sftp.openFile('hamlet.xml', 'readOnly', 'openExisting');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Get the total size of this file (in bytes)
  final bFollowLinks = false;
  final bIsHandle = true;

  // bFollowLinks is ignored because we are passing a handle
  // and not a remote filename.
  // There are alternative methods for handling file sizes
  // greater than 32-bit.  (See the reference documentation.)
  final numBytes = sftp.getFileSize32(handle, bFollowLinks, bIsHandle);
  if (numBytes < 0) {
    print(sftp.lastErrorText);
    return;
  }

  // The charset indicates the character encoding of the text
  // file on the SSH server.   Setting the charset correctly
  // allows the Chilkat SFTP component to correctly interpret
  // the bytes that represent the characters.
  final charset = 'ansi';
  var fileContents = '';
  try {
    fileContents = sftp.readFileText(handle, numBytes, charset);
    print('Received file:');
    print(fileContents);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

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

  print('Success.');
}