随笔 - 165, 文章 - 0, 评论 - 18, 阅读 - 22万
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

asp.net core 通过SFTP下载文件

Posted on   火冰·瓶  阅读(20)  评论(0编辑  收藏  举报

 引用第三方库:Ssh .Net

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
    };
}

  

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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;
}

  

 

相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示