Sample code for 30+ languages & platforms
Rust

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 Rust Downloads

Rust

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

let sftp = chilkat::SFtp::new();

// Set some timeouts, in milliseconds:
sftp.set_connect_timeout_ms(5000);
sftp.set_idle_timeout_ms(15000);

// Connect to the SSH server.  
// The standard SSH port = 22
// The hostname may be a hostname or IP address.
let hostname = "sftp.example.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 file on the server:
let handle = sftp.open_file("hamlet.xml", "readOnly", "openExisting").unwrap_or_default();
if !sftp.last_method_success() {
    println!("{}", sftp.last_error_text());
    return;
}

// Get the total size of this file (in bytes)
let b_follow_links = false;
let b_is_handle = 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.)
let num_bytes = sftp.get_file_size32(&handle, b_follow_links, b_is_handle);
if num_bytes < 0 {
    println!("{}", sftp.last_error_text());
    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.
let charset = "ansi".to_string();
let file_contents = sftp.read_file_text(&handle, num_bytes, &charset).unwrap_or_default();
if !sftp.last_method_success() {
    println!("{}", sftp.last_error_text());
    return;
} else {
    println!("Received file:");
    println!("{}", file_contents);
}

// Close the file.
if sftp.close_handle(&handle).is_err() {
    println!("{}", sftp.last_error_text());
    return;
}

println!("Success.");