Discuss this help topic in SecureBlackbox Forum

SFTP: Download a remote file to a local file or a stream

There exist several ways to download the file from the remote server.

First way is to use DownloadStream() or DownloadFile() method of TElSimpleSFTPClient class to download a single data block which makes a file. DownloadStream() method accepts a reference to the local stream for the data (be it file stream, or memory stream, or BLOB stream or some other stream). DownloadFile() method accepts the absolute path including the name of the local file. Another parameter for the above mentioned methods is the absolute path to the remote file (SFTP doesn't have a concept of "current directory") with the file name.

A simple call to DownloadStream() would look like:


	TElSimpleSFTPClient c = new TElSimpleSFTPClient();
	c.Address = "domain.com";
	MemoryStream ms = new MemoryStream();
	c.DownloadStream(@"/remote/file.dat", ms);
	ms.Position = 0; // reset position in the stream to be able to read the data from it.

If you have more than one file to download, you can use DownloadFiles() method of TElSimpleSFTPClient class. This method accepts the local folder, the standard file mask for remote files and the absolute path to the remote directory (SFTP doesn't have a concept of "current directory"), where the files will be placed. The method lets you perform case conversion of the file names during file download.

Both DownloadStream(), DownloadFile() and DownloadFiles() have TransferMode parameter, which specifies the way how the component behaves when the local file with the specified name exists. Possible options are

  1. skip the existing file
  2. append the data to the end of the remote file
  3. resume the transfer, if the size of the remote data is less than size of the local file
  4. overwrite the data
  5. transfer the data to the file with a new name
  6. rename the existing destination, then transfer the file.

The application is notified about the progress of the single file download operation using OnProgress event of TElSimpleSFTPClient class. DownloadFiles() also notifies the application, when the next file is to be processed, using OnFileOperation() event of TElSimpleSFTPClient class. Using both events you can cancel the download operation.

The most sophisticated and flexible way is to use OpenFile/ Read/ CloseHandle sequence of methods. Use OpenFile() method of TElSimpleSFTPClient class to open the file and get a file handle. The next step is to use Read() method to transfer the data. Don't pass the whole data block to this method. Use chunks which are smaller than 1 Mb. When you finish reading the data, use CloseHandle() method to close the file.

All of the above methods are synchronous and return when the operation is completed.

For information about error handling, see the corresponding how-to article.

How To articles about SFTP client

Discuss this help topic in SecureBlackbox Forum