Dart Requires Chilkat v11.0.0+
Dart
SFTP Read Directory Listing
See more SFTP Examples
Demonstrates how to download a directory listing and iterate over the files.Chilkat Dart Downloads
import 'package:chilkat/chilkat.dart';
void main() {
// This requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Important: It is helpful to send the contents of the
// sftp.LastErrorText property when requesting support.
final sftp = CkSFtp();
// Set some timeouts, in milliseconds:
sftp.connectTimeoutMs = 5000;
sftp.idleTimeoutMs = 10000;
// Connect to the SSH server.
// The standard SSH port = 22
// The hostname may be a hostname or IP address.
final hostname = 'www.my-sftp-server.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 directory on the server...
// Paths starting with a slash are "absolute", and are relative
// to the root of the file system. Names starting with any other
// character are relative to the user's default directory (home directory).
// A path component of ".." refers to the parent directory,
// and "." refers to the current directory.
final String handle;
try {
handle = sftp.openDir('.');
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
// Download the directory listing:
final dirListing = CkSFtpDir();
try {
sftp.readDirListing(handle, dirListing);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
// Close the handle for the directory listing.
try {
sftp.closeHandle(handle);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
// Iterate over the files.
final fileObj = CkSFtpFile();
var i = 0;
final n = dirListing.numFilesAndDirs;
while (i < n) {
try {
dirListing.fileAt(i, fileObj);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
print(fileObj.filename);
print(fileObj.fileType);
print('Size in bytes: ${fileObj.size32}');
print('----');
i++;
}
print('Success.');
}