sftp 递归下载、上传整个文件夹里面的文件

3 篇文章 0 订阅
using Renci.SshNet;
using Renci.SshNet.Sftp;
using System;
using System.IO;
using System.Collections;
using BaseLibrary.ExecutionResults;

namespace BaseLibrary.SSH
{
    /// <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);
                    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="localPath">本地路径</param>
        public ExecutionResult Download(string remotePath, string localPath)
        {
            ExecutionResult exeResult = new ExecutionResult();
            exeResult.Message = string.Empty;
            try
            {
                Connect();

                if (sftp.Exists(remotePath))
                {
                    using (var stream = File.Open(localPath, FileMode.OpenOrCreate))
                    {
                        sftp.DownloadFile(remotePath, stream);
                    }
                    exeResult.Status = true;
                    return exeResult;
                }
                else
                {
                    exeResult.Message = $"Not exist [{remotePath}] on remote SFTP server";
                    exeResult.Status = false;
                    return exeResult;
                }
                    
            }
            catch (Exception ex)
            {
                Disconnect();
                exeResult.Message = ex.Message;
                exeResult.Status = false;
                return exeResult;
            }

        }
        #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);
                //Disconnect();
                File.WriteAllBytes(localPath, byt);
            }
            catch (Exception ex)
            {
                // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件获取失败,原因:{0}", ex.Message));
                Disconnect();
                throw new Exception(string.Format("SFTP文件获取失败,原因:{0}", ex.Message));
                
            }

        }
        #endregion

        #region SFTP获取文件
        /// <summary> 只能读取二层,待修改
        /// SFTP获取文件
        /// </summary>
        /// <param name="remotePath">远程路径</param>
        /// <param name="localPath">本地路径</param>
        public ExecutionResult GetFolder(string remotePath, string localPath)
        {
            ExecutionResult exeResult = new ExecutionResult();
            exeResult.Message = "get the whole folder successfully!";
            try
            {
                Connect();
                var files = sftp.ListDirectory(remotePath);
                foreach (var file in files)
                {
                    try
                    {
                        string name = file.Name;
                        if (file.IsDirectory)
                        {
                            string loacalFolder = localPath + $"\\{file.Name}";
                            if (!Directory.Exists(loacalFolder))
                            Directory.CreateDirectory(loacalFolder);
                            var fs = sftp.ListDirectory(remotePath + "\\" + file.Name);
                            foreach (var f in fs)
                            {
                                if (f.IsDirectory)
                                {

                                }
                                else
                                {
                                    var byt = sftp.ReadAllBytes(f.FullName);//(remotePath + "\\" + file.Name);
                                    File.WriteAllBytes(loacalFolder + "\\" + f.Name, byt);
                                }
                            }
                        }
                        else
                        {
                            var byt = sftp.ReadAllBytes(file.FullName);//(remotePath + "\\" + file.Name);
                            File.WriteAllBytes(localPath + "\\" + file.Name, byt);
                        }
                    }
                    catch
                    {
                        exeResult.Message = $"Exception to copy {file.Name}";
                    }
                }

                Disconnect();                
                exeResult.Status = true;
                //var byt = sftp.ReadAllBytes(remotePath);
                Disconnect();
                //File.WriteAllBytes(localPath, byt);
            }
            catch (Exception ex)
            {
                // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件获取失败,原因:{0}", ex.Message));
                Disconnect();
                //throw new Exception(string.Format("SFTP文件获取失败,原因:{0}", ex.Message));
                exeResult.Message = $"Copy file fail{ex.Message}";

            }

            return exeResult;

        }
        #endregion

        #region SFTP获取文件
        /// <summary> 只能读取二层,待修改
        /// SFTP获取文件
        /// </summary>
        /// <param name="remotePath">远程路径</param>
        /// <param name="localPath">本地路径</param>
        public ExecutionResult RecursionGetFolder(string remotePath, string localPath)
        {
            ExecutionResult exeResult = new ExecutionResult();       
            try
            {
                Connect();
                RecursionCopy(remotePath, localPath);
                Disconnect();
                exeResult.Message = "get the whole folder successfully!";
                exeResult.Status = true;

            }
            catch (Exception ex)
            {
                Disconnect();
                exeResult.Message = $"Copy file fail{ex.Message}";
            }

            return exeResult;
        }
        #endregion

        /// <summary>
        /// 递归Copy
        /// </summary>
        /// <param name="remotePath"></param>
        /// <param name="localPath"></param>
        public void RecursionCopy(string remotePath, string localPath)
        {
            if (!sftp.Exists(remotePath))
            {
                return;
            }
            //
            //var strDesNew = System.IO.Path.Combine(localPath, System.IO.Path.GetFileName(remotePath));
            var strDesNew = localPath;
            if (!Directory.Exists(strDesNew))
            {
                Directory.CreateDirectory(strDesNew);
            }

            var files = sftp.ListDirectory(remotePath);
            if (files == null)
            {
                return;
            }

            foreach (var file in files)
            {
                if (file.IsDirectory)
                {
                    RecursionCopy(file.FullName, strDesNew);
                }
                else
                {
                    var byt = sftp.ReadAllBytes(file.FullName);
                    File.WriteAllBytes(strDesNew + "\\" + file.Name, byt);
                }
            }            
        }

        public void RecursionUpload(string localPath, string remotePath)
        {
            if (!File.Exists(localPath))
            {
                return;
            }
            //
            //var strDesNew = System.IO.Path.Combine(remotePath, System.IO.Path.GetFileName(localPath));
            var strDesNew = remotePath;
            if (!sftp.Exists(strDesNew))
            {
                sftp.CreateDirectory(strDesNew);
            }

            var files = sftp.ListDirectory(localPath);
            if (files == null)
            {
                return;
            }

            foreach (var file in files)
            {
                if (file.IsDirectory)
                {
                    RecursionUpload(file.FullName, strDesNew);
                }
                else
                {
                    var byt = File.ReadAllBytes(file.FullName);
                    sftp.WriteAllBytes(strDesNew + "\\" + file.Name, byt);
                }
            }
        }


        #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 创建目录
        /// <summary>
        /// 创建目录
        /// </summary>
        /// <param name="remotePath">远程目录</param>
        public void CreateDirectory(string remotePath)
        {
            try
            {
                string[] paths = remotePath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                string curPath = "/";
                for (int i = 0; i < paths.Length; i++)
                {
                    curPath += paths[i];
                    if (!sftp.Exists(curPath))
                    {
                        sftp.CreateDirectory(curPath);
                    }
                    if (i < paths.Length - 1)
                        curPath += "/";
                }
            }
            catch (Exception ex)
            {
                if (sftp.IsConnected)
                    Disconnect();
                throw new Exception(string.Format("创建目录失败,原因:{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

    }

}



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 使用 sftp 下载文件夹的命令如下: ``` sftp -r user@remote_host:/remote/directory /local/directory ``` 其中,`-r` 参数表示递归下载整个文件夹,`user` 是远程服务器的用户名,`remote_host` 是远程服务器的主机名或 IP 地址,`/remote/directory` 是要下载的远程文件夹路径,`/local/directory` 是要将文件夹下载到的本地路径。 执行该命令后,sftp 将连接到远程服务器并下载指定的文件夹到本地目录中。请注意,您必须在本地计算机上安装并运行 sftp 客户端,以及远程服务器上的 OpenSSH 服务。 ### 回答2: sftp是一种安全文件传输协议,用于通过SSH连接在本地和远程主机之间传输文件。 要下载一个文件夹,可以按照以下步骤操作: 1. 打开终端或命令提示符窗口,并输入以下命令连接到远程主机: ``` sftp username@hostname ``` 其中,`username`是您在远程主机上的用户名,`hostname`是远程主机的IP地址或域名。 2. 输入密码进行身份验证。 3. 输入以下命令切换到要下载文件夹的路径: ``` cd remote_directory_path ``` 其中,`remote_directory_path`是远程主机上文件夹的路径。 4. 输入以下命令下载整个文件夹及其内容到本地主机: ``` get -r folder_name ``` 其中,`folder_name`是要下载文件夹的名称。 5. 等待传输完成,下载文件夹将保存在当前本地主机工作目录中。 请注意,下载文件夹可能需要一些时间,具体取决于文件夹的大小和网络速度。在下载过程中,请确保网络连接稳定,以免中断传输。 另外,sftp支持的命令还有很多,例如上传文件、删除文件、重命名文件等。您可以通过输入`help`命令来获取更多关于sftp命令的详细信息。 ### 回答3: SFTP是一种安全文件传输协议,用于在远程主机和本地主机之间传输文件。它使用SSH协议进行数据加密和安全认证。在SFTP中,要下载整个文件夹,需要使用递归参数来下载文件夹中的所有文件和子文件夹下载文件夹的命令如下所示: 1. 首先,使用sftp命令连接到远程主机: ``` sftp username@remotehost ``` 2. 输入连接密码,如果需要,则进行身份验证。 3. 导航到要下载文件夹的位置,使用`cd`命令切换目录: ``` cd path/to/folder ``` 4. 使用`lcd`命令设置本地目录,表示将文件下载到本地的指定目录中: ``` lcd path/to/local/folder ``` 5. 使用`get`命令下载整个文件夹: ``` get -r foldername ``` 注意:请将`foldername`替换为要下载文件夹的名称。 这将递归下载文件夹中的所有文件和子文件夹,并将它们保存到您在第4步中指定的本地目录中。 6. 下载完成后,使用`bye`或`exit`命令关闭SFTP连接: ``` bye ``` 或 ``` exit ``` 这将结束SFTP会话并返回到本地命令行。 通过执行上述步骤,您可以使用SFTP下载文件夹。请记住,在下载大型文件夹或带有复杂目录结构文件夹时,可能需要一些时间才能完成下载
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值