Rust Requires Chilkat v11.0.0+
Rust
SFTP Read Directory Listing
See more SFTP Examples
Demonstrates how to download a directory listing and iterate over the files.Chilkat Rust Downloads
// 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.
let sftp = chilkat::SFtp::new();
// Set some timeouts, in milliseconds:
sftp.set_connect_timeout_ms(5000);
sftp.set_idle_timeout_ms(10000);
// Connect to the SSH server.
// The standard SSH port = 22
// The hostname may be a hostname or IP address.
let hostname = "www.my-sftp-server.com".to_string();
let port = 22;
if sftp.connect(&hostname, port).is_err() {
println!("{}", sftp.last_error_text());
return;
}
// Authenticate with the SSH server. Chilkat SFTP supports
// both password-based authenication as well as public-key
// authentication. This example uses password authenication.
if sftp.authenticate_pw("myLogin", "myPassword").is_err() {
println!("{}", sftp.last_error_text());
return;
}
// After authenticating, the SFTP subsystem must be initialized:
if sftp.initialize_sftp().is_err() {
println!("{}", sftp.last_error_text());
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.
let Ok(handle) = sftp.open_dir(".") else {
println!("{}", sftp.last_error_text());
return;
};
// Download the directory listing:
let dir_listing = chilkat::SFtpDir::new();
if sftp.read_dir_listing(&handle, &dir_listing).is_err() {
println!("{}", sftp.last_error_text());
return;
}
// Close the handle for the directory listing.
if sftp.close_handle(&handle).is_err() {
println!("{}", sftp.last_error_text());
return;
}
// Iterate over the files.
let file_obj = chilkat::SFtpFile::new();
let mut i = 0;
let n = dir_listing.num_files_and_dirs();
while i < n {
if dir_listing.file_at(i, &file_obj).is_err() {
println!("{}", dir_listing.last_error_text());
return;
}
println!("{}", file_obj.filename());
println!("{}", file_obj.file_type());
println!("Size in bytes: {}", file_obj.size32());
println!("----");
i = i + 1;
}
println!("Success.");