C# 关于 使用 SFTP 协议上传文件和下载文件

博客介绍了项目连接服务器的注意事项和代码要点。项目需提前添加DiffieHellman.dll、Tamir.SharpSSH.dll,目标框架为.net framework 4以上,之后添加Microsoft.CSharp.dll引用。实例化连接辅助类对象时,sftp地址用目标服务器IP,目标服务器路径用相对路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注意事项:

1、项目需要提前添加DiffieHellman.dll、Tamir.SharpSSH.dll

2、项目 目标框架一定要是 .net framework 4 以上

3、完成以上之后需要添加 Microsoft.CSharp.dll 引用。

代码:

在实例化连接辅助类对象的时候 sftp 地址 为目标服务器的 ip ,不需要其它任何修改,仅需要IP 即可。目标服务器路径要使用相对路径,不需要带上服务器地址。

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

        //host:sftp地址   user:用户名   pwd:密码        
        public SFTPHelper(string host, string user, string pwd)
        {
           
            JSch jsch = new JSch();
            m_session = jsch.getSession(user, host);
            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)
                {
                    m_session.connect();
                    m_channel = m_session.openChannel("sftp");
                    
                    m_channel.connect();
                    m_sftp = (ChannelSftp)m_channel;
                   
                }
                return true;
            }
            catch (System.Exception ex)
            {
                StreamWriter sw1 = System.IO.File.AppendText("C:\\工作\\IsPut.txt");
                sw1.WriteLine("************************");
                sw1.WriteLine(ex.ToString());
                sw1.WriteLine("C");
                sw1.WriteLine(DateTime.Now);
                sw1.WriteLine("************************");
                sw1.Flush();
                sw1.Close();
                return false;
            }
        }

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

        //SFTP存放文件         
        public bool Put(string localPath, string remotePath)
        {
            try
            {
                Connect();
                if (this.Connected)
                {                
                    m_sftp.put(localPath, remotePath);
                    return true;
                }
            }
            catch (System.Exception ex)
            {
                throw new System.Exception(string.Format("SFTP文上传失败,原因:{0}", ex.Message));

            }
            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(remotePath, localPath);
                return true;
            }
            catch (System.Exception ex)
            {
                throw new System.Exception(string.Format("SFTP文件获取失败,原因:{0}", ex.Message));
            }
        }
        //删除SFTP文件
        public bool Delete(string remoteFile)
        {
            try
            {
                //m_sftp.mkdir(remoteFile);
                m_sftp.rm(remoteFile);
                return true;
            }
            catch(System.Exception ex)
            {
                throw new System.Exception(string.Format("SFTP文件删除失败,原因:{0}", ex.Message));

            }
        }

        //获取SFTP文件列表        
        public ArrayList GetFileList(string remotePath, string fileType)
        {
            try
            {
                
                Tamir.SharpSsh.java.util.Vector vvv = m_sftp.ls(remotePath.TrimStart('/'));
                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))
                    { objList.Add(sss); }
                    else { continue; }
                }
                return objList;
            }
            catch (System.Exception ex)
            {
                throw new System.Exception(string.Format("SFTP获取文件列表失败,原因:{0}", ex.Message));

            }
        }

        //登录验证信息        
        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) { }
        }


    }

 

测试实现:

 

 try
                {
                    SFTPHelper helper = new SFTPHelper("74.117.18.120", "APCHINA", "7!Ecru@taTrA");
                    //服务器连接
                    helper.Connect();
 
                    //文件上传
                    helper.Put("C:/test.txt", "/Outbound/test.txt");
                    //文件删除
                    //helper.Delete("/Outbound/test.txt");
                    //获取文件列表
                    helper.GetFileList("/Outbound/", ".txt");

                    //断开连接
                    helper.Disconnect();


                }
                catch (System.Exception ex)
                {

                    StreamWriter sw4 = System.IO.File.AppendText("C:\\Users\\Sapb1gc02\\Desktop\\EDI\\IsPut.txt");
                    sw4.WriteLine("************************");
                    sw4.WriteLine(DateTime.Now);
                    sw4.WriteLine("错误信息");
                    sw4.WriteLine(ex.Message);
                    sw4.WriteLine("************************");
                    sw4.Flush();
                    sw4.Close();
                }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值