Parallel Download

Aug 12, 2013 at 9:50 AM
Edited Aug 12, 2013 at 9:51 AM
Hi, I am very new to SSH.Net. I need to download multiple files within single connection opened. Please let me know how to achieve this. I have tried this by implementing Parallel.ForEach statement, but the issue is, some files are downloaded with 0 kb. Please guide me on this.

Eg: If I want to download ABC.XLSX and XYZ.XLSX files from the server (simultaneously). I am getting the output as ABC.XLSX and XYZ.XLSX with same content / sometimes correct content / sometimes interchanged Content.
Below is my code.
private void ConcurrentDownload()
    {
        // Declaring Connection Information
        PasswordAuthenticationMethod pm = new PasswordAuthenticationMethod("FTPUserName", "Password");
        ConnectionInfo connectionInfo = new ConnectionInfo("FTPHost", 22, "FTPUserName", ProxyTypes.Socks5, "127.0.0.1", 8080, string.Empty, string.Empty, pm);

        using (SftpClient sfc = new SftpClient(connectionInfo))
        {
        // Establish the remote connection
        sfc.Connect();

        // Getting Remote Directory Contents
        IEnumerable<SftpFile> sFiles = new List<SftpFile>();    
        sFiles = sfc.ListDirectory(".\\");

        // Building the File List                
        List<string> remotefiles = new List<string>();
        foreach (SftpFile sfile in sFiles)
        {
         if (!sfile.IsDirectory)
         {
           string ss = sfile.Name;
           remotefiles.Add(ss);
         }
        }

        // Parallel Download
        Parallel.ForEach(remotefiles.Distinct(), file => DownloadFile(sfc, file)); 
        sfc.Disconnect();
        }
    }

   private void DownloadFile(SftpClient sf, string RemoteFileName)
   {
        using (Stream ms = File.OpenWrite(RemoteFileName))
        {
            sf.DownloadFile(RemoteFileName, ms);
        }
   }