訓練家的快寫筆記

The legend of trainer's paper


搜尋:

     關閉     
標題:C# sftp
內容:


using FluentFTP;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Renci.SshNet;

namespace FCUGIS.EOI.NLSCDW.ControlLayer
{
    public class SFTP
    {
        private static string IP
        {
            get
            {
                string res = ConfigurationManager.AppSettings["FTP_IP"].ToString();
                LogHandler.AddBuyWebLog("[Trace]Get Ftp IP:" + res);
                return res;
            }
        }

        /// <summary>
        /// 20190215 申購位子改變成為新位子
        /// </summary>
        private static string NewIP
        {
            get
            {
                string res = ConfigurationManager.AppSettings["NewFTP_IP"].ToString();
                LogHandler.AddBuyWebLog("[Trace]Get Ftp New IP:" + res);
                return res;
            }
        }

        private static string _UserID
        {
            get
            {
                string res = ConfigurationManager.AppSettings["FtpAccount"].ToString();
                LogHandler.AddBuyWebLog("[Trace]Get UserID:" + res);
                return res;
            }
        }

        private static string _PassStr
        {
            get
            {
                string res = ConfigurationManager.AppSettings["FTPPassword"].ToString();
                LogHandler.AddBuyWebLog("[Trace]Get Password:" + res);
                return res;
            }
        }

        /// <summary>
        /// FTP上傳
        /// </summary>
        /// <param name="FullName">完整路徑名</param>
        /// <param name="FtpPath">FTP上傳路徑</param>
        /// <param name="FtpFileName">FTP上傳檔名(未指定時使用原檔名)</param>
        /// <returns></returns>
        public static void UploadFile(string FullName, string FtpPath, string FtpFileName = "")
        {
            try
            {
                string FileName = Path.GetFileName(FullName);

                using (var sftp = new SftpClient(IP, _UserID, _PassStr))
                {
                    sftp.Connect();

                    if (!sftp.Exists(FtpPath))
                    {
                        sftp.CreateDirectory(FtpPath);
                    }

                    string FtpFilePath = FtpPath + FileName;
                    if (!string.IsNullOrEmpty(FtpFileName))
                    {
                        FtpFilePath = FtpPath + FtpFileName;
                    }
                    using (MemoryStream memStream = new MemoryStream())
                    {
                        using (FileStream fstream = new FileStream(FileName, FileMode.Create))
                        {
                            memStream.WriteTo(fstream);

                            memStream.Position = 0;
                            sftp.UploadFile(memStream, FtpFilePath);

                        }
                    }

                }

            }
            catch (Exception ex)
            {
                LogHandler.addLog("[Error]SFTP UploadFile:" + ex.Message);
                LogHandler.addLog("[Error]SFTP UploadFile:" + ex.StackTrace);
                throw;
            }
        }

        /// <summary>
        /// FTP檔案列表
        /// </summary>
        /// <param name="FtpPath">完整路徑名</param>        
        /// <returns></returns>
        public static List<Dictionary<string, string>> ListDirectory(string mIP, string mUserID, string mPws, string FtpPath)
        {
            List<Dictionary<string, string>> output = new List<Dictionary<string, string>>();
            try
            {
                using (var sftp = new SftpClient(mIP, mUserID, mPws))
                {
                    sftp.ConnectionInfo.Encoding = System.Text.Encoding.GetEncoding("BIG5");
                    sftp.Connect();

                    if (!sftp.Exists(FtpPath))
                    {
                        return output;
                    }
                    foreach (var entry in sftp.ListDirectory(FtpPath))
                    {
                        Dictionary<string, string> d = new Dictionary<string, string>();
                        d["TYPE"] = (entry.IsDirectory) ? "DIR" : "FILE";
                        d["FULLNAME"] = entry.FullName;
                        d["SIZE"] = (d["TYPE"] == "FILE") ? entry.Length.ToString() : "-1";
                        d["LASTDATETIME"] = entry.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
                        output.Add(d);
                    }
                }
                return output;
            }
            catch (Exception ex)
            {
                LogHandler.addLog("[Error]SFTP ListDirectory:" + ex.Message);
                LogHandler.addLog("[Error]SFTP ListDirectory:" + ex.StackTrace);
                throw;
            }
        }
        /// <summary>
        /// FTP上傳
        /// </summary>
        /// <param name="FullName">完整路徑名</param>
        /// <param name="FtpPath">FTP上傳路徑</param>
        /// <returns></returns>
        public static void UploadFile(Stream fileStream, string FileName, string FtpPath)
        {
            try
            {
                using (var sftp = new SftpClient(IP, _UserID, _PassStr))
                {
                    sftp.Connect();

                    if (!sftp.Exists(FtpPath))
                    {
                        sftp.CreateDirectory(FtpPath);
                    }

                    using (MemoryStream memStream = new MemoryStream())
                    {
                        memStream.WriteTo(fileStream);
                        memStream.Position = 0;
                        sftp.UploadFile(memStream, FtpPath + FileName);
                    }

                }
            }
            catch (Exception ex)
            {
                LogHandler.addLog("[Error]SFTP UploadFile:" + ex.Message);
                LogHandler.addLog("[Error]SFTP UploadFile:" + ex.StackTrace);
                throw;
            }
        }

        /// <summary>
        /// mySFTP檔案下載 John 改寫的方法
        /// </summary>
        /// <param name="mIP"></param>
        /// <param name="mUserID"></param>
        /// <param name="mPws"></param>
        /// <param name="FtpPath">下載路徑</param>
        /// <returns> null :檔案不存在</returns>
        /// <returns> byte[] :內容</returns>
        public static byte[] mySFTPDownloadFile(string mIP, string mUserID, string mPws, string FtpPath)
        {
            try
            {
                byte[] xfile = null;
                using (var sftp = new SftpClient(mIP, mUserID, mPws))
                {
                    sftp.ConnectionInfo.Encoding = System.Text.Encoding.GetEncoding("BIG5");
                    sftp.Connect();
                    if (sftp.Exists(FtpPath))
                    {
                        xfile = sftp.ReadAllBytes(FtpPath);
                    }

                }
                return xfile;
            }
            catch (Exception ex)
            {
                LogHandler.addLog("[Error]SFTP mySFTPDownloadFile:" + ex.Message);
                LogHandler.addLog("[Error]SFTP mySFTPDownloadFile:" + ex.StackTrace);
                throw;
            }
        }
        /// <summary>
        /// FTP檔案下載
        /// </summary>
        /// <param name="mStream"></param>
        /// <param name="FtpPath">下載路徑</param>
        /// <returns> -1:檔案不存在</returns>
        public static string DownloadFile(Stream mStream, string FtpPath, bool IsNewIP = false)
        {
            try
            {
                string res = "";
                string ftpIP = IP;
                if (IsNewIP)
                    ftpIP = NewIP;
                else
                    ftpIP = IP;


                using (var sftp = new SftpClient(ftpIP, _UserID, _PassStr))
                {
                    sftp.ConnectionInfo.Encoding = System.Text.Encoding.GetEncoding("BIG5");
                    sftp.Connect();

                    if (!sftp.Exists(FtpPath))
                    {
                        sftp.CreateDirectory(FtpPath);
                    }

                    if (!sftp.Exists(FtpPath))
                    {
                        res = "-1";
                    }
                    else
                    {
                        sftp.DownloadFile(FtpPath, mStream);
                    }

                }

                return res;
            }
            catch (Exception ex)
            {
                LogHandler.addLog("[Error]SFTP UploadFile:" + ex.Message);
                LogHandler.addLog("[Error]SFTP UploadFile:" + ex.StackTrace);
                throw;
            }
        }

        /// <summary>
        /// FTP檔案下載
        /// </summary>
        /// <param name="fileContents"></param>
        /// <param name="FtpPath">下載路徑</param>
        /// <returns> -1:檔案不存在</returns>
        public static string DownloadFile(out Byte[] fileContents, string FtpPath, bool IsNewIP = false)
        {
            try
            {
                string res = "";
                string ftpIP = IP;
                if (IsNewIP)
                    ftpIP = NewIP;
                else
                    ftpIP = IP;


                using (var sftp = new SftpClient(ftpIP, _UserID, _PassStr))
                {
                    sftp.ConnectionInfo.Encoding = System.Text.Encoding.GetEncoding("BIG5");
                    sftp.Connect();


                    if (!sftp.Exists(FtpPath))
                    {
                        res = "-1";

                        fileContents = new Byte[] { };
                    }
                    else
                    {
                        using (var ms = new MemoryStream())
                        {
                            sftp.DownloadFile(FtpPath, ms);
                            fileContents = ms.ToArray();
                        }
                    }

                }
                return res;


            }
            catch (Exception ex)
            {
                LogHandler.addLog("[Error]FTP UploadFile:" + ex.Message);
                LogHandler.addLog("[Error]FTP UploadFile:" + ex.StackTrace);
                throw;
            }
        }

        /// <summary>
        /// 指定目標下載檔案
        /// </summary>
        /// <param name="mIP"></param>
        /// <param name="mUserID"></param>
        /// <param name="mPws"></param>
        /// <param name="FtpPath"></param>
        /// <param name="stre"></param>
        /// <returns></returns>
        public static Stream DownloadFile(string mIP, string mUserID, string mPws, string FtpPath)
        {
            try
            {
                Stream res = null;


                using (var sftp = new SftpClient(mIP, mUserID, mPws))
                {
                    sftp.ConnectionInfo.Encoding = System.Text.Encoding.GetEncoding("BIG5");
                    sftp.Connect();

                    if (!sftp.Exists(FtpPath))
                    {
                        res = null;
                    }
                    else
                    {
                        sftp.DownloadFile(FtpPath, res);
                    }


                }

                return res;

            }
            catch (Exception ex)
            {
                LogHandler.addLog("[Error]SFTP DownloadFile:[mIP]" + mIP);
                LogHandler.addLog("[Error]SFTP DownloadFile:[mUserID]" + mUserID);
                LogHandler.addLog("[Error]SFTP DownloadFile:[mPws]" + mPws);
                LogHandler.addLog("[Error]SFTP DownloadFile:[FtpPath]" + FtpPath);
                LogHandler.addLog("[Error]SFTP DownloadFile:" + ex.Message);
                LogHandler.addLog("[Error]SFTP DownloadFile:" + ex.StackTrace);
                throw;
            }
        }

        /// <summary>
        /// 刪除FTP檔案
        /// </summary>
        public static void DeleteFile(string mIP, string mUserID, string mPws, string FtpFilePath, string FtpFileName)
        {
            try
            {
                using (var sftp = new SftpClient(mIP, mUserID, mPws))
                {
                    sftp.Connect();
                    var LstFileName = new List<string>();

                    if (FtpFileName.Contains("*"))
                    {
                        var FileName = FtpFileName.Replace(".*", "");
                        foreach (var fileInfo in sftp.ListDirectory(FtpFilePath))
                        {
                            if (fileInfo.Name.Contains(FileName))
                                LstFileName.Add(fileInfo.Name);
                        }
                    }
                    else
                    {
                        if (sftp.Exists(FtpFilePath))
                            foreach (var fileInfo in sftp.ListDirectory(FtpFilePath))
                            {
                                if (fileInfo.Name.Contains(FtpFileName))
                                    LstFileName.Add(fileInfo.Name);
                            }
                    }
                    foreach (var item in LstFileName)
                    {
                        var Path = $"{FtpFilePath}{item}";

                        if (sftp.Exists(Path))
                            sftp.DeleteFile(Path);
                    }
                }

            }
            catch
            {

                throw;
            }
        }

        /// <summary>
        /// 找尋並刪除路徑下相關檔案名稱的資料
        /// </summary>
        /// <param name="mIP"></param>
        /// <param name="mUserID"></param>
        /// <param name="mPws"></param>
        /// <param name="FtpFilePath"></param>
        /// <param name="FtpFileName"></param>
        public static void DeleteFileUseSearch(string mIP, string mUserID, string mPws, string FtpFilePath, string FtpFileName)
        {
            try
            {
                using (var sftp = new SftpClient(mIP, mUserID, mPws))
                {
                    sftp.Connect();
                    var LstFileName = new List<string>();

                    foreach (var fileInfo in sftp.ListDirectory(FtpFilePath))
                    {
                        if (fileInfo.Name.Contains(FtpFileName))
                            LstFileName.Add(fileInfo.Name);
                    }


                    foreach (var item in LstFileName)
                    {
                        var Path = $"{FtpFilePath}{item}";
                        if (sftp.Exists(Path))
                            sftp.DeleteFile(Path);
                    }

                }

            }
            catch
            {

                throw;
            }
        }

    }
}