我是靠谱客的博主 大气灰狼,最近开发中收集的这篇文章主要介绍c# 使用Renci.SshNet.dll操作SFTP总结,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

1、操作类

    /// <summary>
    /// SFTP操作类
    /// </summary>
    public class SFTPHelper
    {
        #region 字段或属性
        private SftpClient sftp;
        private string cmsimagesIP = ConfigurationManager.AppSettings["cmsimagesIP"].ToString();
        private string cmsimagesName = ConfigurationManager.AppSettings["cmsimagesName"].ToString();
        private string cmsimagesPwd = ConfigurationManager.AppSettings["cmsimagesPwd"].ToString();

        /// <summary>
        /// SFTP连接状态
        /// </summary>
        public bool Connected { get { return sftp.IsConnected; } }
        #endregion

        #region 构造
        /// <summary>
        /// 构造
        /// </summary>
        public SFTPHelper()
        {
            sftp = new SftpClient(cmsimagesIP, 22, cmsimagesName, cmsimagesPwd);
        }
        #endregion

        #region 连接SFTP
        /// <summary>
        /// 连接SFTP
        /// </summary>
        /// <returns>true成功</returns>
        public bool Connect()
        {
            try
            {
                if (!Connected)
                {
                    sftp.Connect();
                }
                return true;
            }
            catch (Exception ex)
            {
                // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("连接SFTP失败,原因:{0}", ex.Message));
                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)
            {
                // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("断开SFTP失败,原因:{0}", ex.Message));
                throw new Exception(string.Format("断开SFTP失败,原因:{0}", ex.Message));
            }
        }
        #endregion

        #region SFTP上传文件
        /// <summary>
        /// SFTP上传文件
        /// </summary>
        /// <param name="localPath">本地路径</param>
        /// <param name="remotePath">远程路径</param>
        public void Put(string localPath, string remotePath, string fileName)
        {
            try
            {
                using (var file = File.OpenRead(localPath))
                {
                    Connect();
                    //判断路径是否存在
                    if (!sftp.Exists(remotePath))
                    {
                        sftp.CreateDirectory(remotePath);
                    }
                    sftp.UploadFile(file, remotePath + fileName);
                    Disconnect();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("SFTP文件上传失败,原因:{0}", ex.Message));
            }
        }
        #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="remotePath">远程目录</param>
        /// <param name="fileSuffix">文件后缀</param>
        /// <returns></returns>
        public ArrayList GetFileList(string remotePath, string fileSuffix)
        {
            try
            {
                Connect();
                var files = sftp.ListDirectory(remotePath);
                Disconnect();
                var objList = new ArrayList();
                foreach (var file in files)
                {
                    string name = file.Name;
                    if (name.Length > (fileSuffix.Length + 1) && fileSuffix == name.Substring(name.Length - fileSuffix.Length))
                    {
                        objList.Add(name);
                    }
                }
                return objList;
            }
            catch (Exception ex)
            {
                // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件列表获取失败,原因:{0}", ex.Message));
                throw new Exception(string.Format("SFTP文件列表获取失败,原因:{0}", ex.Message));
            }
        }
        #endregion

        #region 移动SFTP文件
        /// <summary>
        /// 移动SFTP文件
        /// </summary>
        /// <param name="oldRemotePath">旧远程路径</param>
        /// <param name="newRemotePath">新远程路径</param>
        public void Move(string oldRemotePath, string newRemotePath)
        {
            try
            {
                Connect();
                sftp.RenameFile(oldRemotePath, newRemotePath);
                Disconnect();
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("SFTP文件移动失败,原因:{0}", ex.Message));
            }
        }
        #endregion

        #region 删除SFTP文件
        public void Delete(string remoteFile)
        {
            try
            {
                Connect();
                sftp.Delete(remoteFile);
                Disconnect();
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("SFTP文件删除失败,原因:{0}", ex.Message));
            }
        }
        #endregion

        #region 创建目录
        /// <summary>
        /// 循环创建目录
        /// </summary>
        /// <param name="remotePath">远程目录</param>
        private void CreateDirectory(string remotePath)
        {
            try
            {
                string[] paths = remotePath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                string curPath = "/";
                for (int i = 0; i < paths.Length; i++)
                {
                    curPath += paths[i];
                    if (!sftp.Exists(curPath))
                    {
                        sftp.CreateDirectory(curPath);
                    }
                    if (i < paths.Length - 1)
                    {
                        curPath += "/";
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("创建目录失败,原因:{0}", ex.Message));
            }
        }
        #endregion
    }

 

2、调用

     /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public ActionResult UploadImage(int HotelID, HttpPostedFileBase file)
        {
            if (file == null)
            {
                return Json(new { code = 0, message = "请先选择图片" });
            }
            string batchNo = System.Guid.NewGuid().ToString();
            string fileWebPath = "/upload/" + HotelID + "/";
            string directory = Request.MapPath("~" + fileWebPath);
            string fileName = batchNo + Path.GetExtension(file.FileName);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            string fileFullName = Path.Combine(directory, fileName);
            try
            {
                file.SaveAs(fileFullName);
                //上传SFTP
                SFTPHelper sftp = new SFTPHelper();
                sftp.Put(fileFullName, "/home/cmsimages/ads/cmsimages/choice/" + HotelID + "/", fileName);
                return Json(new { code = 1, message = fileWebPath + fileName });
            }
            catch (Exception e)
            {
                return Json(new { code = 0, message = e.Message });
            }
        }

3、Renci.SshNet.dll下载链接:

 https://download.csdn.net/download/jiduxiaozhang12345/10695019

转载于:https://www.cnblogs.com/len0031/p/9722388.html

最后

以上就是大气灰狼为你收集整理的c# 使用Renci.SshNet.dll操作SFTP总结的全部内容,希望文章能够帮你解决c# 使用Renci.SshNet.dll操作SFTP总结所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(54)

评论列表共有 0 条评论

立即
投稿
返回
顶部