博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

asp.net core 通过SFTP下载文件

Posted on 2024-07-04 11:00  火冰·瓶  阅读(8)  评论(0编辑  收藏  举报

 引用第三方库:Ssh .Net

 

 try
 {
     using (var client = new SftpClient(ftpHost, ftpPort, ftpUsername, ftpPassword))
     {
         client.Connect();
         IEnumerable<ISftpFile> fileEnumerable = client.ListDirectory(remoteDirectory, null).Where(g => !g.IsDirectory & g.Name.Contains(dateStr));//获取到文件列表

         foreach (var file in fileEnumerable)
         {
             var filename = $"{localDirectory}/{file.Name}";//本地需要保存文件的绝对路径
             if (!File.Exists(filename))
             {
                 using (var localFile = File.OpenWrite(filename))
                     client.DownloadFile(file.FullName, localFile);
                 downloadFiles.Add(file.Name);
             }
         }                 
         client.Disconnect();
     }
 }
 catch (SocketException socketExc)
 {
     return new DownloadFileMessage
     {
         Code = DownloadFileCode.Faile,
         Message = "sftp地址连接超时(" + ftpHost + ")" + socketExc.Message
     };
 }
 catch (SshAuthenticationException authenExc)
 {
     return new DownloadFileMessage
     {
         Code = DownloadFileCode.Faile,
         Message = "sftp账号或密码错误(" + ftpUsername + "/" + ftpPassword + ")" + authenExc.Message
     };
 }

  

 

 

 

 try {
     using (var client = new SftpClient(ftpHost, ftpPort, ftpUsername, ftpPassword))
     {
         client.Connect();

         var byt = client.ReadAllBytes(remoteZipPath);  //remoteZipPath是ftp上的路径
         File.WriteAllBytes(localZipPath, byt);  //localZipPath是本地的绝对路径

         client.Disconnect();
     }
 }
 catch (SocketException socketExc) 
 {
     return "\"sftp地址连接超时(\" + ftpHost + \")\" + socketExc.Message";                    
 }
 catch (SshAuthenticationException authenExc)
 {
     return "sftp账号或密码错误(" + ftpUsername + "/" + ftpPassword + ")" + authenExc.Message;
 }
 catch (SftpPathNotFoundException pathNotFoundExc)
 {
     return "sftp没有找到对应的文件(" + remoteZipPath + ")" + pathNotFoundExc.Message;
 }