Sample code for 30+ languages & platforms
Rust

Close a Remote SFTP File or Directory Handle

See more SFTP Examples

Demonstrates the Chilkat SFtp.CloseHandle method, which closes a remote file or directory handle previously returned by OpenFile or OpenDir. The only argument is the handle.

Background: Every opened handle corresponds to state the server holds, and servers cap how many a session may keep open at once, so a long-running program that forgets to close handles will eventually start failing to open new ones. Closing also ensures buffered writes are committed. Once closed, a handle is invalid and must not be reused.

Chilkat Rust Downloads

Rust

// Demonstrates the SFtp.CloseHandle method, which closes a remote file or directory handle.  The
// only argument is the handle returned by OpenFile or OpenDir.

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

// Connect, authenticate, and initialize the SFTP subsystem.
let port = 22;
if sftp.connect("sftp.example.com", port).is_err() {
    println!("{}", sftp.last_error_text());
    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.
let password = "mySshPassword".to_string();

if sftp.authenticate_pw("mySshLogin", &password).is_err() {
    println!("{}", sftp.last_error_text());
    return;
}

if sftp.initialize_sftp().is_err() {
    println!("{}", sftp.last_error_text());
    return;
}

// Open a remote file, obtaining a handle.
let Ok(handle) = sftp.open_file("subdir/data.txt", "readOnly", "openExisting") else {
    println!("{}", sftp.last_error_text());
    return;
};

// ... use the handle ...

// Close the handle to release the server-side resource.  A handle should not be used after it
// is closed.
if sftp.close_handle(&handle).is_err() {
    println!("{}", sftp.last_error_text());
    return;
}

println!("Handle closed.");

sftp.disconnect();