Renci.SshNet进行SFTP连接下载删除上传文件
如果对SFTP or FTPS 有过一点点了解的话,那么你肯定知道Renci.SshNet。
其中SftpClient类的构造函数需要传输,远程服务器地址、端口、用户名、密码(有些还有私钥)。下面只是用到账户密码即可,暂时就不说秘钥了。
当你创建了这个实例之后,就可以Connect();打开服务器连接了。
通过ListDirectory()方法你就可以拿到远程目录的文件了。服务器初始文件目录地址为"/",当你那你子目录或者文件即可进行操作。
通过Delete()方法你可以直接根据远程目录直接删除文件 or 文件夹//"/Test.txt"
通过DownloadFile()方法你可以直接更具远程目录以及创建的文件下载文件。
通过UploadFile()方法你可以把本地文件的流上传到远程目录。
如有问题,我们可以继续探讨。
public class SFTP { #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); } public SFTPOperation(string ip, int port, string user, string pwd) { var authMethods = new List<AuthenticationMethod>(); var keyboardAuthMethod = new KeyboardInteractiveAuthenticationMethod(user);//键盘模拟连接 keyboardAuthMethod.AuthenticationPrompt += delegate (Object senderObject, AuthenticationPromptEventArgs eventArgs) { foreach (var prompt in eventArgs.Prompts) { if (prompt.Request.Equals("Password: ", StringComparison.InvariantCultureIgnoreCase)) { prompt.Response = pwd; } } }; authMethods.Add(new PasswordAuthenticationMethod(user, pwd)); authMethods.Add(keyboardAuthMethod); var connection = new ConnectionInfo(ip, port, user, authMethods.ToArray()); sftp = new SftpClient(connection); sftp.Connect(); } public SFTPOperation(string ip, int port, string user, string passphrase, string keypath) { var key = File.ReadAllText(keypath); PrivateKeyFile keyFile = null; using (var buf = new MemoryStream(Encoding.UTF8.GetBytes(key))) { if (string.IsNullOrWhiteSpace(passphrase)) { keyFile = new PrivateKeyFile(buf); } else { keyFile = new PrivateKeyFile(buf, passphrase); } } var keyFiles = new[] { keyFile }; var methods = new List<AuthenticationMethod> { new PrivateKeyAuthenticationMethod(user, keyFiles) }; var connection = new ConnectionInfo(ip, port, user, methods.ToArray()); sftp = new SftpClient(connection); sftp.Connect(); } #endregion #region 连接SFTP /// <summary> /// 连接SFTP /// </summary> /// <returns>true成功</returns> public bool Connect() { try { if (!Connected) { sftp.Connect(); } return true; } catch (Exception ex) { throw new Exception(string.Format("连接SFTP失败,原因:{0}", ex.InnerException != null ? ex.InnerException.Message : ex.Message)); } } #endregion #region 断开SFTP /// <summary> /// 断开SFTP /// </summary> public void Disconnect() { try { if (sftp != null && Connected) { sftp.Disconnect(); } } catch (Exception ex) { throw new Exception(string.Format("断开SFTP失败,原因:{0}", ex.InnerException != null ? ex.InnerException.Message : ex.Message)); } } #endregion #region SFTP上传文件 /// <summary> /// SFTP上传文件 /// </summary> /// <param name="localPath">本地路径</param> /// <param name="remotePath">远程路径</param> public bool Put(string localPath, string remotePath, bool successCloseConnect = false) { try { using (var file = File.OpenRead(localPath)) { Connect(); sftp.UploadFile(file, remotePath); Console.WriteLine("上传成功"); if (successCloseConnect) { Disconnect(); } } return true; } catch (Exception ex) { throw new Exception(string.Format("SFTP文件上传失败,原因:{0}", ex.InnerException != null ? ex.InnerException.Message : 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 test = sftp.Get(remotePath); var byt = sftp.ReadAllBytes(remotePath); //Disconnect(); //创建写入流 using (var fs = new FileStream(localPath, FileMode.CreateNew)) { var stream = new MemoryStream(byt); byte[] bytes = new byte[1024]; int count = 0; int readCount = 0; //从相应流中读取到的文件大小 while ((count = stream.Read(bytes, 0, bytes.Length)) > 0) { //写入文件 fs.Write(bytes, 0, count); //清空 fs.Flush(); readCount += count; } stream.Close(); var Count = readCount; } } catch (Exception ex) { throw new Exception(string.Format("SFTP文件获取失败,原因:{0}", ex.InnerException != null ? ex.InnerException.Message : ex.Message)); } } public void GetFile(string remotePath, string localPath) { try { //创建写入流 //using (var fs = new FileStream(localPath, FileMode.CreateNew)) using (var fs = File.OpenWrite(localPath)) { sftp.DownloadFile(remotePath, fs); } } catch (Exception ex) { throw new Exception(string.Format("SFTP文件获取失败,原因:{0}", ex.InnerException != null ? ex.InnerException.Message : ex.Message)); } } #endregion #region 删除SFTP文件 /// <summary> /// 删除SFTP文件 /// </summary> /// <param name="remoteFile">远程路径</param> public void Delete(string remoteFile, bool closeClient = false) { try { Connect(); sftp.Delete(remoteFile); if (closeClient) { Disconnect(); } } catch (Exception ex) { throw new Exception(string.Format("SFTP文件删除失败,原因:{0}", ex.InnerException != null ? ex.InnerException.Message : ex.Message)); } } #endregion #region 获取SFTP文件列表 /// <summary> /// 获取SFTP文件列表 /// </summary> /// <param name="remotePath">远程目录</param> /// <param name="fileSuffix">文件后缀</param> /// <returns></returns> public List<string> GetFileList(string remotePath, string fileSuffix) { try { //Connect(); var files = sftp.ListDirectory(remotePath); //Disconnect(); var list = new List<string>(); foreach (var file in files) { string name = file.Name; if (name.Length > (fileSuffix.Length + 1) && fileSuffix == name.Substring(name.Length - fileSuffix.Length)) { list.Add(name); } } return list; } catch (Exception ex) { throw new Exception(string.Format("SFTP文件列表获取失败,原因:{0}", ex.InnerException != null ? ex.InnerException.Message : 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.InnerException != null ? ex.InnerException.Message : ex.Message)); } } #endregion }

浙公网安备 33010602011771号