Download files from SFTP with SSH.NET library

前端 未结 5 1591
眼角桃花
眼角桃花 2020-12-13 04:08
string host = @\"ftphost\";
string username = \"user\";
string password = \"********\";
string localFileName  = System.IO.Path.GetFileName(@\"localfilename\");
strin         


        
5条回答
  •  别那么骄傲
    2020-12-13 04:49

    While the example works, its not the correct way to handle the streams...

    You need to ensure the closing of the files/streams with the using clause.. Also, add try/catch to handle IO errors...

           public void DownloadAll()
        {
            string host = @"sftp.domain.com";
            string username = "myusername";
            string password = "mypassword";
    
            string remoteDirectory = "/RemotePath/";
            string localDirectory = @"C:\LocalDriveFolder\Downloaded\";
    
            using (var sftp = new SftpClient(host, username, password))
            {
                sftp.Connect();
                var files = sftp.ListDirectory(remoteDirectory);
    
                foreach (var file in files)
                {
                    string remoteFileName = file.Name;
                    if ((!file.Name.StartsWith(".")) && ((file.LastWriteTime.Date == DateTime.Today))
    
                        using (Stream file1 = File.OpenWrite(localDirectory + remoteFileName))
                        { 
                            sftp.DownloadFile(remoteDirectory + remoteFileName, file1);
                        }
                }
    
            }
        }
    

提交回复
热议问题