C# 实现本地文件上传SFTP方法

public void Runner()
        {
      #region 上传
            string newFold = DateTime.Today.ToString("yyyy-MM-dd");
            string newTempFold = @"E:\MP_Log\T6000\" + newFold;
            DirectoryInfo dirInfo = new DirectoryInfo(newTempFold);

            // 遍历文件夹中的所有文件
            FileInfo[] files = dirInfo.GetFiles();

            foreach (FileInfo fileInfo in files)
            {

                //Console.WriteLine(fileInfo.LastWriteTime); // 输出路径名
                //Console.WriteLine(fileInfo.FullName); // 输出路径名
                //Console.WriteLine(fileInfo.Name); // 输出文件名

                string ip = "111.11.11.111";//IP
                int port2 = 22;
                string user = "testuser";
                string pwd = "123";
                if (fileInfo.Name.Contains("SATA_"))
                {
                    //校验OBA和FT
                    if (fileInfo.Name.Contains("OBA"))
                    {
                        //上传文件
                        string WO = fileInfo.Name.Substring(5, 19);
                        string localPath = fileInfo.FullName;
                        string tempFold = "/upload/FT_Log/OBA/" + WO;
                        string remotePath = tempFold + "/" + fileInfo.Name;
                        using (var sftp = new SftpClient(ip, port2, user, pwd))
                        {
                            sftp.Connect();
                            if (!sftp.Exists(tempFold))
                            {
                                sftp.CreateDirectory(tempFold);
                            }
                            sftp.Disconnect();
                        }
                        SFTPHelper SFTPHelper = new SFTPHelper(ip, user, pwd, port);
                        SFTPHelper.Put(localPath, remotePath);
                    }
                    else
                    {
                        //上传文件
                        string WO = fileInfo.Name.Substring(5, 19);
                        string localPath = fileInfo.FullName;
                        string tempFold = "/upload/FT_Log/FT/" + WO;
                        string remotePath = tempFold + "/" + fileInfo.Name;
                        using (var sftp = new SftpClient(ip, port2, user, pwd))
                        {
                            sftp.Connect();
                            if (!sftp.Exists(tempFold))
                            {
                                sftp.CreateDirectory(tempFold);
                            }
                            sftp.Disconnect();
                        }
                        SFTPHelper SFTPHelper = new SFTPHelper(ip, user, pwd, port);
                        SFTPHelper.Put(localPath, remotePath);
                    }

                }
                else
                {
                    string localPath = fileInfo.FullName;
                    string tempFold = "/upload/FT_Log/FT/Engineering Tset";
                    string remotePath = tempFold + "/" + fileInfo.Name;
                    using (var sftp = new SftpClient(ip, port2, user, pwd))
                    {
                        sftp.Connect();
                        if (!sftp.Exists(tempFold))
                        {
                            sftp.CreateDirectory(tempFold);
                        }
                        sftp.Disconnect();
                    }
                    SFTPHelper SFTPHelper = new SFTPHelper(ip, user, pwd, port);
                    SFTPHelper.Put(localPath, remotePath);
                }
                Console.WriteLine($"Upload {fileInfo.Name} ok");


            }
            #endregion

        }


        static List<string> GetFiles(string path, string[] patterns)
        {
            List<string> files = new List<string>();
            foreach (var pattern in patterns)
            {
                foreach (var file in Directory.GetFiles(path, pattern))
                {
                    files.Add(file);
                }
            }
            foreach (var directory in Directory.GetDirectories(path))
            {
                files.AddRange(GetFiles(directory, patterns));
            }
            return files;
        }


        
        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 user, string pwd, string port = "22")
            {
                sftp = new SftpClient(ip, Int32.Parse(port), user, pwd);
                Connect();
            }

            ~SFTPHelper()
            {
                Disconnect();
            }
            #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.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.Message));
                }
            }
            #endregion

            #region SFTP上传文件
            /// <summary>
            /// SFTP上传文件
            /// </summary>
            /// <param name="localPath">本地文件全路径 例:G:\\Project\\logo.png</param>
            /// <param name="remotePath">远程路径  例:/logo.png</param>
            public bool Put(string localPath, string remotePath)
            {
                try
                {
                    using (var file = File.OpenRead(localPath))
                    {
                        Connect();
                        sftp.UploadFile(file, remotePath);
                        Disconnect();
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }

            public void CreateDirectoryOnSftp(string tempFold)
            {
                try
                {
                    Connect();
                    if (!Directory.Exists(tempFold))
                    {
                        Directory.CreateDirectory(tempFold);
                    }
                    Directory.CreateDirectory(tempFold);
                    Disconnect();
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("创建文件夹失败,原因:{0}", 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 byt = sftp.ReadAllBytes(remotePath);
                    Disconnect();
                    File.WriteAllBytes(localPath, byt);
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("SFTP文件获取失败,原因:{0}", ex.Message));
                }

            }
            #endregion

            #region 删除SFTP文件
            /// <summary>
            /// 删除SFTP文件 
            /// </summary>
            /// <param name="remoteFile">远程路径</param>
            public void Delete(string remoteFile)
            {
                try
                {
                    Connect();
                    sftp.Delete(remoteFile);
                    Disconnect();
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("SFTP文件删除失败,原因:{0}", ex.Message));
                }
            }
            #endregion


            //抓取文件名称
            public  List<string> GetFileNamesRecursively(string directoryPath)
            {
                List<string> fileNames = new List<string>();

                try
                {
                    // 获取当前目录的文件信息  
                    FileInfo[] files = new DirectoryInfo(directoryPath).GetFiles();

                    // 遍历文件  
                    foreach (FileInfo file in files)
                    {
                        fileNames.Add(file.Name); // 只添加文件名,不包括路径  
                    }

                    // 递归遍历子目录  
                    DirectoryInfo[] directories = new DirectoryInfo(directoryPath).GetDirectories();

                    foreach (DirectoryInfo dir in directories)
                    {
                        fileNames.AddRange(GetFileNamesRecursively(dir.FullName)); // 递归调用自身  
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error occurred: " + ex.Message);
                }

                return fileNames;
            }

            public string SubstringAfter(string source, string searchString)
            {
                int index = source.IndexOf(searchString);
                if (index >= 0)
                {
                    index += searchString.Length;
                    return source.Substring(index);
                }
                return "";
            }


        }
    }
 

  • 13
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值