1 year ago

#388682

test-img

Isaque Neves

What is the best way to use the lib Ionic.Zip (DotNetZip) and SshNet to download a directory via SFTP/SCP directly to a zip file

What is the best way to use the lib Ionic.Zip (DotNetZip) and SshNet to download a directory via SFTP/SCP directly to a zip file, I would like to do this without running out of memory and if possible without having to download it to the local disk first.

I made this code but I'm having memory overflow problems.

static void Main(string[] args)
{
            var connectionInfo = new ConnectionInfo("192.168.133.13", "user",
                                        new PasswordAuthenticationMethod("user", "pass"));
            var client = new SftpClient(connectionInfo);            
            client.Connect();
            DownloadDirectoryAsZip(client, "/var/www/dart/intranetbrowser", @"C:\MyCsharpProjects\fsbackup\download.zip");
            client.Dispose();  
            
}
public static void DownloadDirectoryAsZip(SftpClient sftpClient, string sourceRemotePath, string destLocalPath)
{
            ZipFile zip = new ZipFile();      
            DownloadDirectoryAsZipRec(zip, sftpClient, sourceRemotePath);
            zip.Save(destLocalPath);
            zip.Dispose();
}
private static void DownloadDirectoryAsZipRec(ZipFile zip,SftpClient sftpClient, string sourceRemotePath)
{
         
            IEnumerable<SftpFile> files = sftpClient.ListDirectory(sourceRemotePath);
            foreach (SftpFile file in files)
            {
                if ((file.Name != ".") && (file.Name != ".."))
                {
                    string sourceFilePath = sourceRemotePath + "/" + file.Name;
                  
                    if (file.IsDirectory)
                    {
                        DownloadDirectoryAsZipRec(zip,sftpClient, sourceFilePath);
                    }
                    else
                    {
                        var memoryStream = new MemoryStream();                                               
                        sftpClient.DownloadFile(sourceFilePath, memoryStream);                                                
                        zip.AddEntry(sourceFilePath, memoryStream);                        
                    }
                }
            }
}

c#

zip

sftp

0 Answers

Your Answer

Accepted video resources