Binary vs Text Transfers (SFTP / FTP)

This post clarifies the topic of binary vs. ascii uploads/downloads for SFTP (Secure File Transfer over SSH) and FTP.

Binary mode transmits bytes exactly as-is.   Text mode (also known as “ascii” mode) can modify line endings (CR’s and LF’s) to the canonical convention used on the remote system.  For example, Linux systems typically use bare LF line-endings, whereas text files on Windows typically have CRLF line endings.

The default transfer mode for Chilkat is binary in both SFTP and FTP.

The client-side software (i.e. Chilkat) never explicitly modifies line endings.  For both protocols (SSH/SFTP and FTP), it is the server that may modify line endings when in text/ascii mode.

How to Switch to Text Mode for SFTP:  Methods such as UploadFileByName and DownloadFileByName always operate in binary mode.  It is not possible to use text mode w/ these simplified methods.  To transfer a file in text mode, an application would OpenFile, call Read/Write methods 1 or more times, followed by CloseHandle. For example:

// pseudo-code to upload:
string handle = sftp.OpenFile("remotePath","writeOnly","createNew, textmode");
bool success = sftp.WriteFileText(handle,"utf-8","some text...");
// make additional calls to WriteFileText if needed...
success = sftp.CloseHandle(handle);

How to Switch to ASCII Mode for FTP:  The FTP protocol is entirely different than SSH/SFTP.  An FTP session is in binary mode by default.  A command is sent to change the mode to ASCII mode.  Once changed, all subsequent transfers are ASCII mode until the mode is changed back to binary. Call SetTypeAscii to switch to ASCII mode. Call SetTypeBinary to switch to binary mode.

For example:

// In pseudo-code
success = ftp.SetTypeAscii();
success = ftp.PutFile("someDir/someFile.txt","remoteFile.txt");
success = ftp.SetTypeBinary();
success = ftp.PutFile("someDir/something.jpg","remoteImage.jpg");

You would never upload binary (non-text) files in ASCII mode — it would corrupt the files.  Unless explicitly needed, I would recommend keeping the transfer mode in the default binary mode even for text files.