How to download files from SFTP server in C#
SFTP support in .NET
As in 2022 dotnet still lacks any build-in support for SFTP protocol. In order to download the file using the C# we have to use a third party SFTP library.
This example code uses Rebex SFTP library and connects to the free online SFTP server at test.rebex.net.
Downloading to the filesystem
Following code shows how to download file from an SFTP server in C# and save it to the disk.
using Rebex.Net;
...
// create SFTP client instance
using (var sftp = new Rebex.Net.Sftp())
{
// connect and login to a server
sftp.Connect("test.rebex.net");
sftp.Login("demo", "password");
// download a file
sftp.Download("/readme.txt", @"C:\temp\");
// disconnect (not required, but polite)
sftp.Disconnect();
}
Downloading to the memory stream
Sometimes we don't want to use the diskspace. We only need to get the file content, and process it. It's possible to use the temporary files, but there is a better way how to do it. For example you can download the file to the memory stream. Let's see how to do it:
// download a remote file into a memory stream
var stream = new MemoryStream();
sftp.GetFile("/readme.txt", stream);
// convert memory stream to data
byte[] data = stream.ToArray();
See also
- Public keys, certificates, Single sign-on and other SFTP authentication modes
- Uploading and downloading multiple files
SFTP servers for testing
Want a SFTP server for testing your code? Use one of the following links:
- Tiny SFTP Server: Free, portable minimalist server. Download. Unzip. Run. No setup needed. Read-write.
- test.rebex.net SFTP server: Free online sftp server for testing. No installation needed. Read only.
- Buru SFTP Server for Windows: Full featured SFTP server. Free for personal use.
- sftp.net/servers: Actively maintained collection of SFTP servers, mostly for Windows and Linux.