C#利用Renci.SshNet类库实现SFTP协议操作文件

来源:互联网 发布:梨园淘宝城图片 编辑:程序博客网 时间:2024/06/03 22:44

本文主要是C#利用Renci.SshNet类库实现SFTP文件上传、下载等功能,主要是要引用第三方类库Renci.SshNet.dll。


注意:

1、Renci.SshNet.dll只支持.net framework 4.0及其以上版本。如需开发引用,需安装VS2013以上版本,如需使用,需安装.net framework 4.0

2、Renci.SshNet支持sftp基于ssh协议,同时支持sftp不基于ssh协议


以下是SFTPOperation类,实现了对文件的操作,可供参考。

using System;using System.Collections.Generic; using System.Text;using System;using System.Collections;using System.IO;using Renci.SshNet;namespace SFTPHelper{         /************************描述 SFTP操作类******************************************        **创建者  : aaa        **创建时间: 2015-03-11        **描述: SFTP操作类        *********************************************************************************/        /// <summary>        /// SFTP操作类        /// </summary>        public class SFTPOperation        {            #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 SFTPOperation(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 bool Put(string localPath, string remotePath)            {                bool result = false;                try                {                    using (var file = File.OpenRead(localPath))                    {                        Connect();                        sftp.UploadFile(file, remotePath);                        Disconnect();                        result = true;                    }                }                catch (Exception ex)                {                    //TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件上传失败,原因:{0}", ex.Message));                    throw new Exception(string.Format("SFTP文件上传失败,原因:{0}", ex.Message));                }                return result;            }            #endregion            #region SFTP获取文件            /// <summary>            /// SFTP获取文件            /// </summary>            /// <param name="remotePath">远程路径</param>            /// <param name="localPath">本地路径</param>            public bool  Get(string remotePath, string localPath)            {                bool result = false;                try                {                    Connect();                    var byt = sftp.ReadAllBytes(remotePath);                    Disconnect();                    File.WriteAllBytes(localPath, byt);                    result = true;                }                catch (Exception ex)                {                    //TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件获取失败,原因:{0}", ex.Message));                    throw new Exception(string.Format("SFTP文件获取失败,原因:{0}", ex.Message));                }                return result;            }            #endregion            #region 删除SFTP文件            /// <summary>            /// 删除SFTP文件             /// </summary>            /// <param name="remoteFile">远程路径</param>            public void Delete(string remoteFile)            {                try                {                    Connect();                    sftp.Delete(remoteFile);                    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="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)                {                    //TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件移动失败,原因:{0}", ex.Message));                    throw new Exception(string.Format("SFTP文件移动失败,原因:{0}", ex.Message));                }            }            #endregion        }    }  


使用方法:

vb.net

</pre><pre name="code" class="vb">Dim sftp As SFTPOperation = New SFTPOperation("192.168.1.10",22, abc, 123456) 'sftp IP,端口号,用户名,密码sftp.Connect()Dim sftpFileName As String = "/sftpFile/aa.txt"   'sftp上面的文件路径及文件名sftp.Put("E:\loadFile\abc.txt", sftpFileName)   '上传:本地路径及本地文件名,sftp上文件路径及文件名。上传之后可自动改名,也可以不改名
<span style="font-family: Arial, Helvetica, sans-serif;">sftp.Get("/sftpFile/aa.txt","E:\loadFile\abc.txt")  '下载:sftp上文件路径及文件名,本地路径及本地文件名。下载之后可自动改名,也可以不改名</span>
<span style="font-family: Arial, Helvetica, sans-serif;">sftp.Disconnect()</span>


实例下载地址:利用Renci.SshNet类库实现sftp文件操作

0 0
原创粉丝点击