C# SFTP / Renci.SshNet

最近需要通过SFTP来获取文件。

下面是我整理的相关信息。

以下只是大致代码,大家看看就行了。

我的是window service。每天会去下载文件。

1  下载 Renci.SshNet

通过 nuget查找 sshnet,下载Renci.SshNet。

我们可以看到一些常用方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Renci.SshNet;
using System.Collections;
using System.IO;

namespace Terminal_CDMA
{

    /// <summary>
    /// SFTP操作类
    /// </summary>
    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 port, string user, string pwd)
        {
            sftp = new SftpClient(ip, Int32.Parse(port), user, pwd);
        }
        #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)
        {
            try
            {
                using (var file = File.OpenRead(localPath))
                {
                    Connect();
                    sftp.UploadFile(file, remotePath);
                }
            }
            catch (Exception ex)
            {
                // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件上传失败,原因:{0}", ex.Message));
                throw new Exception(string.Format("SFTP文件上传失败,原因:{0}", ex.Message));
            }
            finally
            {
                Disconnect();
            }
        }
        #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);
                File.WriteAllBytes(localPath, byt);
            }
            catch (Exception ex)
            {
                // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件获取失败,原因:{0}", ex.Message));
                throw new Exception(string.Format("SFTP文件获取失败,原因:{0}", ex.Message));
            }
            finally
            {
                Disconnect();
            }

        }
        #endregion

        #region 重命名SFTP文件
        /// <summary>
        /// 重命名SFTP文件 
        /// <param name="oldFile">旧远程路径</param>  
        /// <param name="newFile">新远程路径</param> 
        /// </summary>
        public void Rename_SFTP(string oldFilePath,string newFilePath)
        {
            try
            {
                Connect();
                sftp.RenameFile(oldFilePath, newFilePath);
            }
            catch (Exception ex)
            {
                // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件删除失败,原因:{0}", ex.Message));
                throw new Exception(string.Format("SFTP文件删除失败,原因:{0}", ex.Message));
            }
            finally
            {
                Disconnect();
            }
        }
        #endregion

        #region 删除SFTP文件
        /// <summary>
        /// 删除SFTP文件 
        /// </summary>
        /// <param name="remoteFile">远程路径</param>
        public void Delete(string remoteFile)
        {
            try
            {
                Connect();
                sftp.Delete(remoteFile);
            }
            catch (Exception ex)
            {
                // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件删除失败,原因:{0}", ex.Message));
                throw new Exception(string.Format("SFTP文件删除失败,原因:{0}", ex.Message));
            }
            finally
            {
                Disconnect();
            }
        }
        #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);
                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));
            }
            finally
            {
                Disconnect();
            }
        }
        #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)
            {
                // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件移动失败,原因:{0}", ex.Message));
                throw new Exception(string.Format("SFTP文件移动失败,原因:{0}", ex.Message));
            }
            finally
            {
                Disconnect();
            }
        }
        #endregion

    }
}

2  window service

public partial class Service1 : ServiceBase
    {
        DAL.DAL dal = new DAL.DAL();
        public Service1()
        {
            InitializeComponent();
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            //运行
            RunService();
        }

        System.Timers.Timer timer1 = new System.Timers.Timer(MyConfig.interval);
        static SFTPHelper sftp = new SFTPHelper(MyConfig.host, MyConfig.port, MyConfig.username, MyConfig.password);
        protected override void OnStart(string[] args)
        {
            //正式
            if (!MyConfig.IsDebug)
            {
                timer1.AutoReset = true;
                timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
                timer1.Enabled = true;
            }
        }

        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (DateTime.Now.Hour == MyConfig.timerStart)
            {
                RunService();
            }
        }

        public void RunService()
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            LogHelper.WriteLog("  <<==开始______________________" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "______________________==>>");

            DataTable dt1 = UploadInboundPO();
            DataTable dt2 = ReadSJ_SNAP();
            DataTable dt3 = ReadSHP();
            DataTable dt4 = ReadRcv_Results();
            int UploadInboundPO_Count = dt1 == null?0: dt1.Rows.Count;
            int ReadSJ_SNAP_Count = dt2 == null ? 0 : dt2.Rows.Count;
            int ReadSHP_Count = dt3 == null ? 0 : dt3.Rows.Count;
            int ReadRcv_Results_Count = dt4 == null ? 0 : dt4.Rows.Count;
            SendEmail(dt1, dt2, dt3, dt4);
            LogHelper.WriteLog(string.Format("---------------------InboundPO :{0}-----------------------", UploadInboundPO_Count));
            LogHelper.WriteLog(string.Format("---------------------SJ_SNAP :{0}-----------------------", ReadSJ_SNAP_Count));
            LogHelper.WriteLog(string.Format("---------------------SHP :{0}-----------------------", ReadSHP_Count));
            LogHelper.WriteLog(string.Format("---------------------Rcv_Results :{0}-----------------------", ReadRcv_Results_Count));
            LogHelper.WriteLog("  <<==结束______________________" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "______________________==>>");

            Clear();
        }

        //上传InboundPO
        public DataTable UploadInboundPO()
        {
            try
            {
                //业务逻辑
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message);
                return null;
            }
        }

        //读取SJ_SNAP
        public DataTable ReadSJ_SNAP()
        {
            try
            {
                //获取文件SJ_SNAP
                sftp.Get(MyConfig.OutboundPath + MyConfig.fileName_SJ_SNAP, MyConfig.uploadFilePath_SJ_SNAP + MyConfig.fileName_SJ_SNAP);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("SJ_SNAP.csv -- " + ex.Message);
                return null;
            } 
 
//业务逻辑 return dt; 
        //发送邮件         
        public void SendEmail(DataTable InboundPO, DataTable SJ_SNAP, DataTable SHP,DataTable Rcv_Results)         
        {             
            //生成邮件body             
            //string emailHtml1 = InboundPO == null ? "" : dal.GetSJ_SNAP_Html(InboundPO);             
            string emailHtml2 = SJ_SNAP == null ? "" : dal.GetSJ_SNAP_Html(SJ_SNAP);             
            string emailHtml3 = SHP == null ? "" : dal.GetSHP_Html(SHP);             
            //string emailHtml4 = Rcv_Results == null ? "" : dal.GetSJ_SNAP_Html(Rcv_Results);             
            string[] files = { file_NewPath_InboundPO, file_NewPath_SJ_SNAP, file_NewPath_SHP, file_NewPath_Rcv_Results };             
            //发送邮件             
            EmailHelper.SendMailByEmail(files, DateTime.Now.ToShortDateString() + "的三聚库存", (emailHtml2+ emailHtml3), EmailHelper.emailReceiver.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList());         
        }         
        public void Clear()         
        {             
            file_NewPath_InboundPO = "";             
            file_NewPath_SJ_SNAP = "";             
            file_NewPath_SHP = "";             
            file_NewPath_Rcv_Results = "";         
        }         
        protected override void OnStop()         
        {             
            //正式             
            timer1.Enabled = false;         
        }         
        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)         
        {             
            try             
            {                 
                Exception ex = e.ExceptionObject as Exception;                 
                string exStr = "
" + "
" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") 
                    + ex.Message + "详细信息如下:
"+ Environment.NewLine + "[InnerException]" 
                    + ex.InnerException + "
"                                     
                    + Environment.NewLine + "[Source]" 
                    + ex.Source + "
"                                     
                    + Environment.NewLine + "[TargetSite]" 
                    + ex.TargetSite + "
"                                     
                    + Environment.NewLine + "[StackTrace]" 
                    + ex.StackTrace + "
";                 
                LogHelper.WriteLog(exStr);             
            }             
            catch { }             
            finally { }         
        }
原文地址:https://www.cnblogs.com/hanjun0612/p/9779769.html