none
C# - SFTP keep connection to FTP server to download multiple times RRS feed

  • Question

  • Hi

    I would like to be able to keep the connection to the FTP server after downloading the file, but it keep logging in and disconnecting after each download.

    The code:

    using Renci.SshNet;
    using Renci.SshNet.Sftp;
    
            static void SftpDownload()
            {
                string host = @"sftp.server";
                string username = "username";
                string password = @"password";
    
                string localpath = "C:/Temp/";
    
                // Path to file on SFTP server
                string pathRemoteFile = "/data.txt";
                // Path where the file should be saved once downloaded (locally)
                System.IO.Directory.CreateDirectory(localpath);
                string pathLocalFile = (localpath + "/data.txt");
    
                using (SftpClient sftp = new SftpClient(host, username, password))
                {
                    try
                    {
                        while (Program.ftpcon == true)
                        {
                            sftp.Connect();
    
                            Program.ftpcon = false;
                        }
    
                        using (Stream fileStream = File.OpenWrite(pathLocalFile))
                        {
                            sftp.DownloadFile(pathRemoteFile, fileStream);
                        }
    
                        // Disabled due to heavy load on FTP server
                        //sftp.Disconnect();
                    }
                    catch (Exception er)
                    {
                        Console.WriteLine("An exception has been caught " + er.ToString());
                    }
                }
            }

    (ftpcon is defined outside)

    Any help is greatly appriciated!



    • Edited by P DOGG Wednesday, April 11, 2018 11:10 AM
    • Moved by CoolDadTx Wednesday, April 11, 2018 1:52 PM Third party product
    Wednesday, April 11, 2018 11:08 AM

All replies

  • There is no SftpClient in .NET. You are referring to a third party library that we don't have access to. This forum is for C#-specific questions. We have no way of knowing how they implement their logic and whether what you want to do is possible. You need to post this question in their forums.

    Michael Taylor http://www.michaeltaylorp3.net

    Wednesday, April 11, 2018 1:52 PM