首页 > 编程语言 >C# 通过SshNet上传下载文件

C# 通过SshNet上传下载文件

时间:2023-12-22 09:33:40浏览次数:30  
标签:strSourceFolderName string uploadfile C# 上传下载 SshNet Length client public

会把本地文件夹压缩成 .tar.gz 文件 后上传

using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Tar;
using Renci.SshNet;
using System;
using System.IO;
using System.Windows.Forms;

namespace Pack
{
    public delegate void AddTextLog(string log);

    public class SShHelp
    {
        public string ip { get; set; }
        public int port { get; set; }
        public string userName { get; set; }
        public string password { get; set; }
        public AddTextLog addTextLog { get; set; }

        public SShHelp()
        {
           
        }

        public SShHelp(string ip, int port,string userName,string password, AddTextLog _addTextLog)
        {
            this.ip = ip;
            this.port = port;
            this.userName = userName;
            this.password = password;
            _instance = this;
            _instance.addTextLog = _addTextLog;
        }

        private static SShHelp _instance = null;

        public static SShHelp Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new SShHelp();
                }
                return _instance;
            }
        }

        public void ExecuteCommand(string commandText)
        {
            SshClient ssh = new SshClient(ip, port, userName, password);
            ssh.Connect();
            SshCommand cmd = ssh.CreateCommand(commandText);
            cmd.Execute();
            AddLog($"[{userName}]# " + commandText);
            AddLog(cmd.Result);
            if (cmd.Error.Length > 0) AddLog("警告" + cmd.Error);
            ssh.Dispose();
        }

        public void AddLog(string text)
        {
            text = text.Replace("\n", "\r\n");
            if (text.IndexOf("\r\n") == -1)
            {
                text += "\r\n";
            }
            addTextLog(text);
        }


        public string Upload(string workingdirectory, string uploadfile)
        {
            var path = uploadfile.Split('\\');
            string directoryPath = "";
            string strSourceFolderName = "";

            if ((uploadfile.IndexOf(".tar.gz") == -1 && uploadfile.IndexOf(".") > -1 && uploadfile.IndexOf(".db") == -1) || Directory.Exists(uploadfile))
            {
                if (strSourceFolderName.Length == 0)
                    strSourceFolderName = path[path.Length - 1];
                directoryPath = uploadfile.Substring(0, uploadfile.Length - strSourceFolderName.Length);
                if (!CreatTarGzArchive(uploadfile.Substring(0, uploadfile.Length - strSourceFolderName.Length), strSourceFolderName))
                {
                    MessageBox.Show($"上传{uploadfile}失败", "提示:");
                    return string.Empty;
                }
                strSourceFolderName += ".tar.gz";
            }
            using (var client = new SftpClient(ip, port, userName, password)) //创建连接对象
            {
                client.Connect(); //连接
                client.ChangeDirectory(workingdirectory); //切换目录
                var listDirectory = client.ListDirectory(workingdirectory); //获取目录下所有文件
                foreach (var fi in listDirectory) //遍历文件
                {
                    // Console.WriteLine(" - " + fi.Name);
                    // client.DeleteFile(fi.FullName);//删除文件
                }
                string newPath = uploadfile;
                if (!string.IsNullOrEmpty(directoryPath))
                {
                    if (directoryPath.Substring(directoryPath.Length - 2).IndexOf("\\") > -1)
                    {
                        newPath = directoryPath + strSourceFolderName;
                    }
                    else
                    {
                        newPath = directoryPath + "\\" + strSourceFolderName;
                    }
                }

                using (var fileStream = new FileStream(newPath, FileMode.Open))
                {
                    client.BufferSize = 4 * 1024;
                    client.UploadFile(fileStream, Path.GetFileName(newPath));
                    AddLog("上传:" + workingdirectory + "->" + uploadfile);
                }
            }
            if(strSourceFolderName.Length == 0)
            {
                strSourceFolderName = path[path.Length - 1];
            }
            return strSourceFolderName;
        }

        /// <summary>  
        /// 生成  文件  
        /// </summary>  
        /// <param name="strBasePath">文件基目录(源文件、生成文件所在目录)</param>  
        /// <param name="strSourceFolderName">待压缩的源文件夹名</param>  
        public bool CreatTarGzArchive(string strBasePath, string strSourceFolderName)
        {
            if (string.IsNullOrEmpty(strBasePath)
                || string.IsNullOrEmpty(strSourceFolderName)
                || !System.IO.Directory.Exists(strBasePath)
                || !System.IO.Directory.Exists(Path.Combine(strBasePath, strSourceFolderName)))
            {
                return false;
            }

            Environment.CurrentDirectory = strBasePath;
            string strSourceFolderAllPath = Path.Combine(strBasePath, strSourceFolderName);
            string strOupFileAllPath = Path.Combine(strBasePath, strSourceFolderName + ".tar.gz");

            Stream outTmpStream = new FileStream(strOupFileAllPath, FileMode.OpenOrCreate);

            //注意此处源文件大小大于4096KB  
            Stream outStream = new GZipOutputStream(outTmpStream);
            TarArchive archive = TarArchive.CreateOutputTarArchive(outStream, TarBuffer.DefaultBlockFactor);
            TarEntry entry = TarEntry.CreateEntryFromFile(strSourceFolderAllPath);
            archive.WriteEntry(entry, true);

            if (archive != null)
            {
                archive.Close();
            }
            outTmpStream.Close();
            outStream.Close();
            return true;
        }


        /// <summary>
        /// SFTP获取文件
        /// </summary>
        /// <param name="remotePath">远程路径</param>
        /// <param name="localPath">本地路径</param>
        public void DownloadFiles(string remotePath, string localPath)
        {
            using (var client = new SftpClient(ip, port, userName, password)) //创建连接对象
            {
                client.Connect(); 
                var byt = client.ReadAllBytes(remotePath);
                File.WriteAllBytes(localPath, byt);
            }
        }

    }
}

 

标签:strSourceFolderName,string,uploadfile,C#,上传下载,SshNet,Length,client,public
From: https://www.cnblogs.com/ctrlc-ctrlv/p/17920576.html

相关文章

  • 【c# winform】devexpress treeList右键菜单添加按钮
    本文提供俩种不需要手动添加编辑控件方法。方法一:创建新的右键菜单添加“执行选择”按钮,且抑制TreeList自带菜单结果展示: 代码: privatevoidForm1_Load(objectsender,EventArgse){CreateBarButtonItem();}privatevoidCreateBarButtonItem(){//创建右键......
  • core-js引起的报错
    从git上获取的代码突然运行不起来,报错提示含有[email protected]:core-js@<3.23.3isnolongermaintainedandnotrecommendedforusageduetothenumberofissues.BecauseoftheV8enginewhims,featuredetectioninoldcore-jsversionscouldcause......
  • C++ Qt开发:StandardItemModel数据模型组件
    Qt是一个跨平台C++图形界面开发库,利用Qt可以快速开发跨平台窗体应用程序,在Qt中我们可以通过拖拽的方式将不同组件放到指定的位置,实现图形化开发极大的方便了开发效率,本章将重点介绍StandardItemModel数据模型组件的常用方法及灵活运用。QStandardItemModel是Qt中用于存储标准......
  • 采集终端adc测量电阻不准问题
    现象:测量端接一个200欧姆的电阻,adc测量得出电阻值为260左右,为什么测量的不准?原理图:思考过程:硬件问题排查,不是硬件问题;单片机adc外设配置问题,下载例程,发现不是adc外设配置问题;分析测量电阻原理,是电压变化范围太小原因(如下图);结论:这是一个简单的测量电阻电路,需要根据要测量......
  • Qt/C++视频监控Onvif工具/组播搜索/显示监控画面/图片参数调节/OSD管理/祖传原创
    一、前言能够写出简单易用而又不失功能强大的组件,一直是我的追求,简单主要体现在易用性,不能搞一些繁琐的流程和一些极难使用的API接口,或者一些看不懂的很难以理解的函数名称,一定是要越简单越好。功能强大主要体现在功能的完整性,常规的接口肯定是必备的,然后在默认值方面,尽量将值设......
  • 【Python】【OpenCV】定位条形码(二)
    根据上一篇博客可知,单纯的通过求取最大面积而进行定位的局限性,因此我们接下来将通过cv2.moments()和cv2.HuMoments()这两个方法来在更复杂的环境中去找到我们的目标区域。 cv2.moments():参数:array:表示输入图像的单通道数组。通常是灰度图像,可以是8位或浮点型。binaryIm......
  • 如何在 Git 书写良好的 Commit Messages
    如何在Git书写良好的CommitMessagesWhy(为什么编写)|How(如何编写)WhyMessagesAdiffwilltellyouwhatchanged,butonlythecommitmessagecanproperlytellyouwhy良好的Messages可以告诉人们变更的原因,更好高效地理解几个月前甚至几年前发生的事情。......
  • django验证码插件 --- django-simple-captcha
    使用django-simple-captcha实现登录验证码: 第一步:安装pillow依赖pipinstallpillow  -ihttps://pypi.tuna.tsinghua.edu.cn/simple/ 第二步:安装django-simple-captchapipinstalldjango-simple-captcha -ihttps://pypi.tuna.tsinghua.edu.cn/simple/ 第三步:注......
  • Spring-IOC
     1.前言1) 框架:spring的本质就是一个容器,放java对象的容器,java对象在spring容器中也叫做bean对象。项目启动的时候,把bean对象放到IOC容器中,当需要使用对象的时候,直接从容器中拿出来使用。2) 框架作用:提高开发效率;增强可重用性;提供编......
  • Excel导入导出
    POI--------》Workbook接口HSSFWorkbook:这个实现类是我们早期使用最多的对象,它可以操作Excel2003以前(包含2003)的所有Excel版本。在2003以前Excel的版本后缀还是.xlsXSSFWorkbook:这个实现类现在在很多公司都可以发现还在使用,它是操作的Excel2003--Excel2007......