Chilkat.SFtp Class Overview

Chilkat.SFtp provides Secure File Transfer Protocol functionality over SSH. It supports connecting to an SSH/SFTP server, authenticating with passwords or private keys, initializing the SFTP subsystem, uploading and downloading files, reading and writing by file handle, listing directories, managing remote files and attributes, synchronizing directory trees, using proxies, throttling bandwidth, and diagnosing SFTP/SSH status errors.

What the Class Is Used For

Use Chilkat.SFtp when an application needs secure file transfer over SSH. SFTP is not FTP and does not use FTP concepts such as a current remote directory. Paths are either absolute from the server filesystem root or relative to the authenticated user’s home directory.

Secure File Transfer Upload and download files by path, by open file handle, or directly to and from BinData, StringBuilder, byte arrays, and local files.
SSH Authentication Authenticate with password, private key, password plus private key, secure-string variants, keyboard-interactive authentication, or stored secrets.
Remote File Management Create/remove directories, delete files, rename or move files, create symbolic and hard links, inspect file existence, and manage file attributes.
Directory Synchronization Upload or download directory trees using synchronization modes and filename / directory wildcard filters.

Typical Workflow

  1. Configure optional connection settings such as ConnectTimeoutMs, IdleTimeoutMs, proxy settings, PreferIpv6, algorithm restrictions, or host key handling.
  2. Call Connect(host, port) to establish the SSH transport connection. Port 22 is typical.
  3. Verify or record the server identity using HostKeyFingerprint, GetHostKeyFP, and ServerIdentifier.
  4. Authenticate with AuthenticatePw, AuthenticatePk, AuthenticatePwPk, secure-string variants, or keyboard-interactive authentication.
  5. Call InitializeSftp to start the SFTP subsystem. This negotiates the SFTP protocol version and prepares the object for file operations.
  6. Perform file or directory operations such as DownloadFileByName, UploadFileByName, OpenDir, ReadDirListing, OpenFile, or synchronization methods.
  7. Close any open file or directory handles with CloseHandle.
  8. Call Disconnect when finished.
Required sequence: A normal SFTP session is ConnectAuthenticate*InitializeSftp → file operations.

Core Concepts

Concept Meaning Important Members
SSH Transport SFTP runs over SSH. The first step is establishing the encrypted SSH connection to the server. Connect, Disconnect, IsConnected, SendIgnore
Authentication Login happens after the SSH connection is established and before SFTP is initialized. AuthenticatePw, AuthenticatePk, AuthenticatePwPk, StartKeyboardAuth
SFTP Subsystem The file-transfer subsystem that must be initialized after authentication. InitializeSftp, ProtocolVersion, ForceV3
Remote Paths Absolute paths begin with /. Relative paths are relative to the authenticated user’s home directory. RealPath, OpenFile, OpenDir, DownloadFileByName
Handles Some operations open a remote file or directory and return a handle. The handle is then used for reads, writes, attributes, or closing. OpenFile, OpenDir, CloseHandle
Attribute Cache Optional cache for file size and attributes to reduce repeated server round-trips when using path-based attribute methods. EnableCache, ClearCache

Connection, Authentication, and Initialization

Step Members Guidance
Connect Connect Connects to the SSH/SFTP server. The host may be a domain name, IPv4 address, or IPv6 address.
Authenticate with password AuthenticatePw Use when the server accepts username/password authentication.
Authenticate with private key AuthenticatePk Use when the corresponding public key is installed on the server.
Authenticate with password and key AuthenticatePwPk Use only for servers configured to require both factors.
Use secure strings AuthenticateSecPw, AuthenticateSecPwPk Secure-string variants of password-based authentication methods.
Keyboard-interactive authentication StartKeyboardAuth, ContinueKeyboardAuth, UserAuthBanner Use when the SSH server presents one or more interactive prompts.
Initialize SFTP InitializeSftp Starts the SFTP subsystem after authentication. If it fails while opening the SFTP channel, check InitializeFailCode and InitializeFailReason.
Stored secrets: Set EnableSecrets = true to allow supported password inputs such as AuthenticatePw, AuthenticatePwPk, HttpProxyPassword, and SocksPassword to use secure-storage specifiers beginning with !!.

SFTP Protocol Version

ProtocolVersion is set after InitializeSftp. Some SFTP features depend on the negotiated protocol version.

Member Purpose Important Detail
ForceV3 Forces protocol version 3 even when the server supports a higher version. Defaults to true. Set to false when version 4–6 features are needed and the server supports them.
ProtocolVersion Shows the negotiated SFTP protocol version, usually between 3 and 6. Older versions may not support some file dates, attributes, or open-file options.
Version-dependent attributes GetFileCreateTimeStr, SetCreateDt, CopyFileAttr Creation times and some flags are not available on older protocol versions.

Path Rules

Path Form Meaning Example
Absolute path Starts at the root of the server filesystem. /home/joe/data/report.csv
Relative path Relative to the authenticated user’s home directory. ./data/report.csv
Empty directory path Refers to the user’s default directory, usually the home directory. ""
Canonical path Ask the server to resolve a path into an absolute canonical path. RealPath
No current remote directory: SFTP is not FTP. Methods such as OpenDir do not change a remote working directory. Use explicit absolute or relative paths. If a simple filename such as test.txt fails with a folder-not-found error, try ./test.txt.

Uploads and Downloads

Task Methods Use When
Download local file by remote path DownloadFileByName Simplest path-based download. Date preservation requires PreserveDate = true.
Download using an open handle DownloadFile Use after OpenFile. Streams data from server to local file with no file-size limitation.
Download into memory objects DownloadBd, DownloadSb Download directly into BinData or StringBuilder.
Resume download ResumeDownloadFileByName Continues a partial local download based on the current local file size.
Upload local file by remote path UploadFileByName Simplest path-based upload. Date preservation requires PreserveDate = true.
Upload using an open handle UploadFile Use after OpenFile when handle-based control is needed.
Upload from memory objects UploadBd, UploadSb Upload from BinData or StringBuilder, with character encoding control for text.
Resume upload ResumeUploadFileByName Continues an upload based on the current remote file size.
Upload reliability: If UploadFile or UploadFileByName fails with a connection-aborted condition, try reducing UploadChunkSize, such as to 4096. Smaller chunks may be slower but can avoid some host/network aborts.

Opening Files and Reading/Writing by Handle

OpenFile returns a remote file handle. Use that handle with read/write methods, then close it with CloseHandle.

OpenFile Argument Allowed Values Meaning
access readOnly, writeOnly, readWrite Controls whether the handle can read, write, or both.
Required create disposition createNew, createTruncate, openExisting, openOrCreate, truncateExisting One of these keywords must be present.
Optional create flags appendData, appendDataAtomic, textMode, blockRead, blockWrite, blockDelete, noFollow, deleteOnClose Many optional flags require SFTP protocol version 5 or later.
Need Methods Notes
Sequential binary reads ReadFileBytes, ReadFileBd, AccumulateBytes Read a number of bytes from an open file. Repeat until Eof(handle) is true.
Offset binary reads ReadFileBytes32, ReadFileBytes64, ReadFileBytes64s Read bytes from a specified offset. The string-based method is for environments without 64-bit integer support.
Text reads ReadFileText, ReadFileText32, ReadFileText64, ReadFileText64s Reads bytes and decodes them using the specified charset.
Binary writes WriteFileBytes, WriteFileBytes32, WriteFileBytes64, WriteFileBytes64s, WriteFileBd Write byte data to an open file, optionally at a specific offset.
Text writes WriteFileText, WriteFileText32, WriteFileText64, WriteFileText64s Encodes text using the supplied charset before writing.
Read status Eof, LastReadFailed, LastReadNumBytes Inspect EOF and the result of the last read on a handle.
Text-read caution: Text read methods specify a number of bytes, not characters. With multi-byte encodings such as UTF-8 or Shift_JIS, the last character could be partially read if the read ends in the middle of a character.

Directory Listing and Filtering

Task Members Guidance
Open a directory OpenDir Returns a directory handle. This does not change any remote working directory.
Read directory listing ReadDirListing Reads the contents of an opened directory into an SFtpDir object.
Close directory handle CloseHandle Close the handle returned by OpenDir.
Include dot directories IncludeDotDirs If true, directory listings include . and ...
Only include matching names ReadDirMustMatch Semicolon-separated wildcard list such as *.xml;*.txt;*.csv.
Exclude matching names ReadDirMustNotMatch Semicolon-separated wildcard list of names to exclude.

Remote File and Directory Management

Task Method Notes
Check path existence and type FileExists Returns 0 if missing, positive values for regular files, directories, symlinks, and other filesystem entry types, or -1 if unable to check.
Create directory CreateDir Creates a directory on the SFTP server.
Remove directory RemoveDir Most SFTP servers require the directory to be empty before deletion.
Remove file RemoveFile Deletes a remote file.
Rename or move file/directory RenameFileOrDir Renames a remote file or directory. Also used to move a file to another path.
Read symbolic link target ReadLink Returns the target of a symbolic link.
Create symbolic link SymLink Creates a symbolic link on the server.
Create hard link HardLink Uses the hardlink@openssh.com extension and works only when the server supports it.
Flush remote file to storage Fsync Uses the fsync@openssh.com extension and works only when the server supports it.

File Attributes

Attribute Get Methods Set Methods
Size GetFileSize32, GetFileSize64, GetFileSizeStr Not directly set by an attribute method.
Create time GetFileCreateTimeStr SetCreateDt, SetCreateTimeStr
Last-access time GetFileLastAccessStr SetLastAccessDt, SetLastAccessTimeStr
Last-modified time GetFileLastModifiedStr SetLastModifiedDt, SetLastModifiedTimeStr
Owner and group GetFileOwner, GetFileGroup SetOwnerAndGroup
Permissions GetFilePermissions SetPermissions
Copy local file attributes to remote file Local file is the source. CopyFileAttr
Path or handle: Attribute methods generally accept either a remote path or an open file handle. Set the isHandle / bIsHandle argument correctly.

Directory Tree Synchronization

Direction Method Purpose
Remote to local SyncTreeDownload Downloads files from the SFTP server to a local directory tree.
Local to remote SyncTreeUpload Uploads a local directory tree to the SFTP server.
Get transfer list GetSyncedFiles Returns paths transferred by the last sync operation, relative to the sync root.
Sync Filter Applies To Example
SyncMustMatch Only transfer files matching one of these patterns. *.xml;*.txt;*.csv
SyncMustNotMatch Do not transfer files matching these patterns. *.tmp;*.bak
SyncMustMatchDir Only enter directories matching one of these patterns. data_*;reports
SyncMustNotMatchDir Do not enter directories matching these patterns. archive;temp
SyncCreateAllLocalDirs Download sync directory creation. Controls whether empty remote directories are created locally.
SyncDirectives Sync behavior modifiers. UploadIgnoreLocalOpenFailures
Mode Download Behavior Upload Behavior
0 Download all files. Upload all files.
1 Download files that do not exist locally. Upload files that do not exist on the server.
2 Download newer or non-existent files. Upload newer or non-existent files.
3 Download only newer files that already exist locally. Upload only newer files that already exist on the server.
4 Not listed for download. Transfer missing files or files with size differences.
5 Download missing files or files with size differences. Same as mode 4, but also newer files.
6 Same as mode 5, but also newer files. Not listed for upload.
99 Do not download; delete remote files that do not exist locally. Not listed for upload.

Performance and Transfer Control

Need Members Guidance
Throttle download speed BandwidthThrottleDown Nonzero value limits download bandwidth to approximately that many bytes per second.
Throttle upload speed BandwidthThrottleUp Nonzero value limits upload bandwidth to approximately that many bytes per second.
Track active transfer count XferByteCount, XferByteCount64 Read during asynchronous or long-running transfers. For sync operations, this is cumulative across all transferred files.
Progress callback granularity PercentDoneScale Controls the scale used for PercentDone callbacks in event-capable environments.
Abort long operation AbortCurrent, HeartbeatMs Allows synchronous or asynchronous network/file operations to be aborted.
Socket tuning SoRcvBuf, SoSndBuf, TcpNoDelay Usually leave defaults. Adjust only for performance troubleshooting.

Proxy, Tunneling, and Network Options

Scenario Members Purpose
HTTP proxy HttpProxyHostname, HttpProxyPort, HttpProxyUsername, HttpProxyPassword, HttpProxyAuthMethod, HttpProxyDomain Connect to the SFTP server through an HTTP proxy using Basic or NTLM proxy authentication.
SOCKS proxy SocksVersion, SocksHostname, SocksPort, SocksUsername, SocksPassword Connect through SOCKS4 or SOCKS5.
Connect through another SSH server ConnectThroughSsh Routes SFTP connection through an existing connected and authenticated Ssh object. The target server still requires its own authentication.
Use a specific local IP ClientIpAddress Use for multi-homed systems that must bind the outgoing connection to a specific local address.
Prefer IPv6 PreferIpv6 Chooses IPv6 over IPv4 when both are available for a domain.

Security and Algorithm Controls

Need Members Guidance
Verify server identity HostKeyFingerprint, GetHostKeyFP Use after connecting to compare the server’s host key fingerprint to the expected value.
Force one cipher ForceCipher Restricts the connection to a specific cipher. Connection fails if the server does not support it.
Specify allowed algorithms SetAllowedAlgorithms Provides JSON-based control over the exact algorithm set allowed for the SSH/SFTP connection.
Legacy RSA userauth compatibility UncommonOptions = "ForceUserAuthRsaSha1" Use before connecting when a server still requires SHA-1 for RSA public-key user authentication.
Reject weak MAC algorithms UncommonOptions = "no-weak-mac-algs" Removes weaker MAC algorithms from the negotiation list.
Re-enable selected disabled algorithms +ssh-hmac-etm, +chacha20-poly1305@openssh.com Compatibility options for explicitly re-adding algorithms disabled by default behavior described in the reference.
Policy vs compatibility: Tightening algorithms can satisfy security policy, but it can also prevent connections to older or unusually configured servers.

Diagnostics and Troubleshooting

Problem Area Members What to Check
General failure LastErrorText Full diagnostic text for the last method or property call.
Structured diagnostic data GetLastJsonData Retrieves additional JSON details for selected methods.
SFTP status response LastStatusCode, LastStatusMessage Contains the last SSH_FXP_STATUS code and server-provided message, such as no such file, permission denied, invalid handle, or no space.
Authentication failure AuthFailReason, PasswordChangeRequested Distinguishes transport failure, invalid key, unsupported methods, protocol error, incorrect credentials, already authenticated, or password-change request.
SFTP initialization failure InitializeFailCode, InitializeFailReason Explains channel-open failures during InitializeSftp, such as administratively prohibited, connect failed, unknown channel type, or resource shortage.
Server disconnect DisconnectCode, DisconnectReason Reports the SSH disconnect code and descriptive reason if the server sent a DISCONNECT message.
Session trace KeepSessionLog, SessionLog, ClearSessionLog Enables a growing in-memory log of SFTP communications for debugging.
Connection still valid? IsConnected, SendIgnore IsConnected is the last known state. Use SendIgnore to actively test the connection.

Common Pitfalls

Pitfall Better Approach
Treating SFTP like FTP and expecting a current remote directory. Always pass explicit absolute or home-relative paths. Use ./filename for files relative to the user’s home directory when needed.
Calling file operations before InitializeSftp. Always complete Connect, Authenticate*, and InitializeSftp first.
Leaving file or directory handles open. Close handles returned by OpenFile or OpenDir with CloseHandle.
Assuming IsConnected actively checks the socket. Use SendIgnore when the application needs a real connection check.
Expecting creation time or advanced open flags while forcing SFTP v3. Check ProtocolVersion and set ForceV3 = false when the server supports higher versions and those features are needed.
Assuming file attribute cache updates automatically after external changes. Use ClearCache when cached attributes may be stale.

Best Practices

Recommendation Reason
Verify the host key fingerprint after connecting. SSH/SFTP security depends on confirming the server identity.
Set practical timeout values. ConnectTimeoutMs controls TCP connection wait time, while IdleTimeoutMs controls stalled SFTP send/receive progress.
Use simple path-based methods for common transfers. DownloadFileByName and UploadFileByName are easiest for normal file transfer.
Use handle-based methods for partial reads/writes, offsets, append modes, or advanced open flags. OpenFile provides lower-level control.
Use sync filters for large directory-tree operations. SyncMustMatch, SyncMustNotMatch, SyncMustMatchDir, and SyncMustNotMatchDir prevent unnecessary traversal and transfer.
Enable PreserveDate before simple uploads/downloads when timestamps matter. Timestamp preservation is not automatic by default.
Use EnableSecrets instead of hard-coded passwords where supported. Credentials can be resolved from Windows Credential Manager or Apple Keychain at runtime.
Check LastStatusCode and LastStatusMessage for server-side file errors. They often identify file-not-found, permission, invalid-handle, and filesystem errors more directly than a generic failure.
Use LastErrorText for support diagnostics. It provides the most complete Chilkat diagnostic information.

Summary

Chilkat.SFtp is the main Chilkat class for secure file transfer over SSH. It provides SSH connection and authentication, SFTP subsystem initialization, simple and handle-based upload/download APIs, directory listing, remote file management, file attributes, sync-tree upload/download, bandwidth throttling, proxy support, host key fingerprinting, algorithm controls, and detailed diagnostics.

For most applications, the key pattern is simple: connect, authenticate, initialize SFTP, perform file operations using explicit paths, close any handles, and disconnect. Use the handle-based APIs and synchronization methods when more control is needed.