Downloading SFTP files in console applications.

I use the WinSCP dll to download files from SFTP sites in SSDT, as shown here, but this approach doesn’t work in .NET Core applications as the WinSCP dll isn’t available as a NuGet package.

An alternative to WinSCP is SSH.NET, which amoung other things, has the ability to download files from SFTP sites.

After installing the package something like the below will work to download all files from an SFTP site.

// Check sftp site for files
string host = @"<HOST_NAME>";
string username = "<USER_NAME>";
string password = "<PASSWORD>";

string remoteDirectory = "<REMOTE_DIRECTORY>";
string localDirectory = @"<LOCAL_DIRECTORY>";

using (var sftp = new SftpClient(host, username, password))
	IEnumerable<SftpFile> sftpFiles = sftp.ListDirectory(remoteDirectory);

	foreach (SftpFile sftpFile in sftpFiles)
		string remoteFileName = sftpFile.Name;
		if (!sftpFile.Name.StartsWith("."))
			using (Stream fileStream = File.OpenWrite(localDirectory + remoteFileName))
				sftp.DownloadFile(remoteDirectory + remoteFileName, fileStream);

			sftp.DeleteFile(remoteDirectory + remoteFileName);

Leave a Reply

Your email address will not be published. Required fields are marked *