C# 使用Renci.SshNet.dll操作SFTP,实现数据传输

1、Renci.SshNet.dll下载链接: https://download.youkuaiyun.com/download/yigu4011/87959164

2、SFTP操作帮助类:

public class SFTPHelper
    {
        #region 字段或属性
        private SftpClient sftp;
        /// <summary>
        /// SFTP连接状态
        /// </summary>
        public bool Connected { get { return sftp.IsConnected; } }
        #endregion

        #region 构造
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="ip">IP</param>
        /// <param name="port">端口</param>
        /// <param name="user">用户名</param>
        /// <param name="pwd">密码</param>
        public SFTPHelper(string ip, string user, string pwd, string port = "22")
        {
            sftp = new SftpClient(ip, Int32.Parse(port), user, pwd);
            Connect();
        }

        ~SFTPHelper()
        {
            Disconnect();
        }
        #endregion

        #region 连接SFTP
        /// <summary>
        /// 连接SFTP
        /// </summary>
        /// <returns>true成功</returns>
        public bool Connect()
        {
            try
            {
                if (!Connected)
                {
                    sftp.Connect();
                }
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("连接SFTP失败,原因:{0}", ex.Message));
            }
        }
        #endregion

        #region 断开SFTP
        /// <summary>
        /// 断开SFTP
        /// </summary> 
        public void Disconnect()
        {
            try
            {
                if (sftp != null && Connected)
                {
                    sftp.Disconnect();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("断开SFTP失败,原因:{0}", ex.Message));
            }
        }
        #endregion

        #region SFTP上传文件
        /// <summary>
        /// SFTP上传文件
        /// </summary>
        /// <param name="localPath">本地文件全路径 例:G:\\Project\\logo.png</param>
        /// <param name="remotePath">远程路径  例:/logo.png</param>
        public bool Put(string localPath, string remotePath)
        {
            try
            {
                using (var file = File.OpenRead(localPath))
                {
                    Connect();
                    sftp.UploadFile(file, remotePath);
                    Disconnect();
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion

        #region SFTP获取文件
        /// <summary>
        /// SFTP获取文件
        /// </summary>
        /// <param name="remotePath">远程路径</param>
        /// <param name="localPath">本地路径</param>
        public void Get(string remotePath, string localPath)
        {
            try
            {
                Connect();
                var byt = sftp.ReadAllBytes(remotePath);
                Disconnect();
                File.WriteAllBytes(localPath, byt);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("SFTP文件获取失败,原因:{0}", ex.Message));

            }

        }
        #endregion

        #region 删除SFTP文件
        /// <summary>
        /// 删除SFTP文件 
        /// </summary>
        /// <param name="remoteFile">远程路径</param>
        public void Delete(string remoteFile)
        {
            try
            {
                Connect();
                sftp.Delete(remoteFile);
                Disconnect();
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("SFTP文件删除失败,原因:{0}", ex.Message));
            }
        }
        #endregion



    }

调用:

1、上传文件:

private void UploadLabel(string remotePath, string localFile, string remoteFileName)
        {
            SFTPHelper sftp = new SFTPHelper(labelServerInfo.LabelServerIp, labelServerInfo.LabelServerUser, labelServerInfo.LabelServerPassWord,labelServerInfo.LabelServerPort);
            if (!sftp.CheckDirectoryExist(sftp.RemotePath, remotePath))
            {
                string remotepath = "/" + remotePath + "/";
                
                if (!sftp.MakeDirectory(remotepath))
                {
                    AppendTextColorful("Create Remote Path Error,Path already exists", Color.Orange, true);
                }
            }
            else
            {
                string remotepath = "/" + remotePath + "/";
                sftp.RemotePath = remotepath;
            }
            sftp.RemotePath = "/" + remotePath + "/";

            if (sftp.CheckFileExist(remoteFileName))
            {
                if (DialogResult.Yes != MessageBox.Show("Remote File is Exist, Override ?", "Message:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) { return; }
                if (!sftp.Delete(sftp.RemotePath + remoteFileName))
                {
                    AppendTextColorful("Delete Remote File Error", Color.Red, true);
                }
                if (!sftp.Put(localFile, sftp.RemotePath + remoteFileName))
                {
                    AppendTextColorful("Upload Remote File Error", Color.Red, true);
                }
                else
                {
                    AppendTextColorful("Upload Remote File OK", Color.Blue, true);
                }
            }
            else
            {
                if (!sftp.Put(localFile, sftp.RemotePath + remoteFileName))
                {
                    AppendTextColorful("Upload Remote File Error", Color.Red, true);
                }
                else
                {
                    AppendTextColorful("Upload Remote File OK", Color.Blue, true);
                }
            }
        }

2、下载文件:

private void DownLoadLabel(string remotePath,string remoteFile,string localFileName)
        {
            try
            {
                SFTPHelper sftp = new SFTPHelper(labelServerInfo.LabelServerIp, labelServerInfo.LabelServerUser, labelServerInfo.LabelServerPassWord, labelServerInfo.LabelServerPort);
                sftp.RemotePath = "/" + remotePath + "/";

                if (!sftp.CheckFileExist(remoteFile))
                {
                    AppendTextColorful("Remote File Not Exist", Color.Red, true);
                    return;
                }

                if (!sftp.Get(sftp.RemotePath+remoteFile, localFileName))
                {
                    AppendTextColorful("Download Remote File Error", Color.Red, true);
                }
                else
                {
                    AppendTextColorful("Download Remote File OK", Color.Blue, true);

                }
            }
            catch (Exception ex) { AppendTextColorful(ex.Message, Color.Red, true); }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

痕迹灬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值