码迷,mamicode.com
首页 > 其他好文 > 详细

SFTP文件下载

时间:2015-11-27 10:33:49      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

首先需要引用nuget包:

Install-Package Tamir.SharpSSH 

SFTPHELPER文件提供方法:

using Tamir.SharpSsh;
using Tamir.SharpSsh.jsch;
//----------------需要包含的命名空间

public class SFTPHelper
    {
        private Session m_session;
        private Channel m_channel;
        private ChannelSftp m_sftp;

        log4net.ILog log = log4net.LogManager.GetLogger("SFTPDownload");

        //host:sftp地址   user:用户名   pwd:密码          
        public SFTPHelper(string host, string user, string pwd)
        {
            string[] arr = host.Split(:);
            string ip = arr[0];
            int port = 22;
            if (arr.Length > 1) port = Int32.Parse(arr[1]);

            JSch jsch = new JSch();            
            m_session = jsch.getSession(user, ip, port);
            //log.Info("m_session:"+m_session.ToString()+" - "+m_session.isConnected());
            MyUserInfo ui = new MyUserInfo();
            ui.setPassword(pwd);
            m_session.setUserInfo(ui);            
        }

        //SFTP连接状态          
        public bool Connected { get { return m_session.isConnected(); } }

        //连接SFTP          
        public bool Connect()
        {
            try
            {
                if (!Connected)
                {
                    //log.Info("start connect 1");
                    //m_session.setClientVersion("SSH-2.0-SharpSSH-1.1.1.13-JSCH-0.1.28");
                    
                    m_session.connect();
                    //log.Info("start connnect 2");
                    m_channel = m_session.openChannel("sftp");
                    m_channel.connect();
                    //log.Info("channel connect");
                    m_sftp = (ChannelSftp)m_channel;
                    //log.Info(m_session.getServerVersion()+" - "+m_session.getClientVersion());
                }
                return true;
            }
            catch(Exception exp)
            {
                log.Info("登陆失败原因:"+exp.ToString());
                return false;
            }
        }

        //断开SFTP          
        public void Disconnect()
        {
            if (Connected)
            {
                m_channel.disconnect();
                m_session.disconnect();
            }
        }

        //SFTP存放文件          
        public bool Put(string localPath, string remotePath)
        {
            try
            {
                Tamir.SharpSsh.java.String src = new Tamir.SharpSsh.java.String(localPath);
                Tamir.SharpSsh.java.String dst = new Tamir.SharpSsh.java.String(remotePath);
                m_sftp.put(src, dst);
                return true;
            }
            catch
            {
                return false;
            }
        }

        //SFTP获取文件          
        public bool Get(string remotePath, string localPath)
        {
            try
            {
                Tamir.SharpSsh.java.String src = new Tamir.SharpSsh.java.String(remotePath);
                Tamir.SharpSsh.java.String dst = new Tamir.SharpSsh.java.String(localPath);
                m_sftp.get(src, dst);
                return true;
            }
            catch(Exception exp)
            {
                log.Info("文件下载失败原因:" + exp.ToString());
                return false;
            }
        }
        //删除SFTP文件  
        public bool Delete(string remoteFile)
        {
            try
            {
                m_sftp.rm(remoteFile);
                return true;
            }
            catch (Exception exp)
            {
                log.Info("文件删除失败原因:" + exp.ToString());
                return false;
            }
        }

        //获取SFTP文件列表          
        public ArrayList GetFileList(string remotePath, string fileType)
        {
            try
            {
                Tamir.SharpSsh.java.util.Vector vvv = m_sftp.ls(remotePath);
                ArrayList objList = new ArrayList();
                foreach (Tamir.SharpSsh.jsch.ChannelSftp.LsEntry qqq in vvv)
                {
                    string sss = qqq.getFilename();
                    if (sss.Length > (fileType.Length + 1) && fileType == sss.Substring(sss.Length - fileType.Length) && sss != "." && sss!= "..")
                    { objList.Add(sss); }
                    else { continue; }
                }

                return objList;
            }
            catch (Exception exp)
            {
                log.Info("文件列表获取失败原因:" + exp.ToString());
                return null;
            }
        }


        //登录验证信息          
        public class MyUserInfo : UserInfo
        {
            String passwd;
            public String getPassword() { return passwd; }
            public void setPassword(String passwd) { this.passwd = passwd; }

            public String getPassphrase() { return null; }
            public bool promptPassphrase(String message) { return true; }

            public bool promptPassword(String message) { return true; }
            public bool promptYesNo(String message) { return true; }
            public void showMessage(String message) { }
        }


    }

调用上面的文件:

public void DownFtpFiles()
        {
            //log4net.Config.XmlConfigurator.Configure();
            
            while (true)
            {                   
                SFTPHelper sftphelper = new SFTPHelper(ftpIP, ftpUserName, ftpPassword);
                try{                    
                    System.Threading.Thread.Sleep(10000);
                    log.Info("开始登陆FTP服务器");                    
                    //LogHelper.WriteLog("开始登陆FTP服务器");
                    bool bconn = sftphelper.Connect();
                    if (bconn)
                    {
                        log.Info("登陆成功");
                        ArrayList objList = new ArrayList();
                        objList = sftphelper.GetFileList(ftpRoot, "dat");
                        log.Info("文件列表获取成功");

                        string fileName = null;
                        foreach (object obj in objList)
                        {
                            string fileUrl = obj.ToString();
                            fileName = fileUrl;
                            try
                            {                               
                                
                                    log.Info("开始下载," + fileUrl);
                                    sftphelper.Get(ftpRoot + "/" + fileUrl, tempFileDir + "\\" + fileName);
                                    File.Move(tempFileDir + "\\" + fileName, downloadFileDir + "\\" + fileName);

                                    //记录到已下载的列表中
                                    //this.AppendDownloaded(fileUrl);
                                    //删除远程文件
                                    sftphelper.Delete(ftpRoot + "/" + fileUrl);

                                    log.Info("下载成功," + ftpRoot + "/" + fileUrl);
                                
                            }
                            catch (Exception exp)
                            {
                                log.Info("下载或移动失败," + fileUrl + ",原因是:" + exp.ToString());
                            }
                        }

                    }
                    else
                    {
                        log.Info("登陆失败");
                    }
                }                 
                catch (Exception exp)
                {
                    log.Info("下载或移动失败,原因是:" + exp.ToString());
                }
                finally
                {
                    try
                    {
                        sftphelper.Disconnect();                        
                    }
                    catch (Exception ex)
                    {
                        log.Info("关闭FTP连接异常,原因是:" + ex.ToString());
                    }
                }
            }
        }

 

SFTP文件下载

标签:

原文地址:http://www.cnblogs.com/WZH75171992/p/4999655.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!