How to download files from SFTP server in C#

  |   Martin Vobr

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

SFTP servers for testing

Rebex Tiny SFTP Server

Want a SFTP server for testing your code? Use one of the following links: