使用Renci.SshNet实现sftp文件上传和下载


最近有个项目需要使用sftp上传和下载文件,在.Net 中我没有找到现成的类库可用(有知道的有劳告知我,也好学习一下 大笑),sftp我也不需要太多介绍,网上一大堆,感兴趣的可以去soso啊。

下面我简单贴出我实现的代码,防止我忘记,以后有需要,可以直接到这里Copy,haha。。。

public class sFtpHelper
    {
        public static int DownloadFtp(string filePath, string localPath, string fileName, string ftpServerIP, string ftpPort, string ftpUserID, string ftpPassword)
        {
            string localFileName = localPath + "\\" + fileName;
            string remoteFileName = $"/{filePath}/{fileName}";

            try
            {
                using (var sftp = new SftpClient(ftpServerIP, Convert.ToInt32(ftpPort), ftpUserID, ftpPassword))
                {
                    sftp.Connect();

                    using (var file = File.OpenWrite(localFileName))
                    {
                        sftp.DownloadFile(remoteFileName, file);
                    }

                    sftp.Disconnect();
                    Log.getInstace().WriteSysInfo($"下载文件{localFileName}成功", "info");

                    Console.WriteLine($"下载文件成功,文件路径:{localFileName}");
                    return 0;
                }
            }
            catch (Exception e)
            {
                Log.getInstace().WriteSysInfo($"下载文件{localFileName}失败,原因:{e}", "err");
                Console.WriteLine($"下载失败,原因:{e}");
                return -2;
            }
        }

        public static int UploadFtp(string filePath, string localPath, string filename, string ftpServerIP, string ftpPort, string ftpUserID, string ftpPassword)
        {
            string localFileName = localPath + "\\" + filename;
            string remoteFileName = $"/{filePath}/{filename}";

            try
            {
                using (var sftp = new SftpClient(ftpServerIP, Convert.ToInt32(ftpPort), ftpUserID, ftpPassword))
                {
                    sftp.Connect();

                    using (var file = File.OpenWrite(localFileName))
                    {
                        sftp.UploadFile( file,remoteFileName);
                    }

                    sftp.Disconnect();
                    Log.getInstace().WriteSysInfo($"上传文件{localFileName}成功", "info");
                    Console.WriteLine($"上传文件成功,文件路径:{localFileName}");
                    return 0;
                }
            }
            catch (Exception e)
            {
                Log.getInstace().WriteSysInfo($"上传文件{localFileName}失败,原因:{e}", "err");
                Console.WriteLine($"上传失败,原因:{e}");
                return -2;
            }
        }

    }

使用方法是在项目中引用Renci.SshNet.dll类库,类库下载地址:https://yunpan.cn/cRePDjuevZF9b  访问密码 8c5e




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值