I am trying to download files asynchronously from an SFTP-server using SSH.NET. If I do it synchronously, it works fine but when I do it async, I get empty files. This is my code:
var port = 22;
string host = "localhost";
string username = "user";
string password = "password";
string localPath = @"C:\temp";
using (var client = new SftpClient(host, port, username, password))
{
client.Connect();
var files = client.ListDirectory("");
var tasks = new List<Task>();
foreach (var file in files)
{
using (var saveFile = File.OpenWrite(localPath + "\\" + file.Name))
{
//sftp.DownloadFile(file.FullName,saveFile); <-- This works fine
tasks.Add(Task.Factory.FromAsync(client.BeginDownloadFile(file.FullName, saveFile), client.EndDownloadFile));
}
}
await Task.WhenAll(tasks);
client.Disconnect();
}