用於同步服務器文件的一款FTP 客戶端工具開發

因生產需要,開發一款工具用於同步服務器端的文件,爲了避免產線員工由於誤操作拷貝錯文件的情況出現。其開發過程記錄如下:

1.先下載FTP Server

https://download.csdn.net/download/ericwuhk/12026363

2.配置好參數

①設置本機IP地址  Edit->Setting->Passive mode setting->use the following IP

②生成證書Edit->Setting->FTP over TLS,並設置密碼 

③設置好用戶名密碼

④設置本地用於FTP傳輸的共享文件夾,如E:\008.SharedImage,並勾選所有文件屬性,點擊set as home dir

⑤重新啓動FileZilla Server, 出現Logged on 說明配置成功。此時在文件瀏覽器種輸入ftp://127.0.0.1/  可正常訪問FTP文件夾,如image

3.編寫好界面,並寫好FTPClient類庫

using System;
using System.Net;
using System.IO;
using System.Text;
using System.Net.Sockets;
using BaseLibrary.ExecutionResults;

namespace BaseLibrary.FTP
{
    public class FTPClient
    {
        #region 登陸字段、屬性         
        public string strServerIP;///FTP服務器IP地址 
        public int serverPort;/// FTP服務器端口                            
                
        public string strUserID;///登錄用戶賬號         
        public string strPassword;//// 用戶登錄密碼          
        public Boolean isConnected;/// 是否登錄狀態
        private string strRemotePath; //當前服務器目錄
        #endregion

        #region 消息應答字段
        private string m_Message;
        public string Message
        {
            get { return this.m_Message; }
            set { this.m_Message = value; }
        }
        private string m_ReplyString;
        public string ReplyString
        {
            get { return this.m_ReplyString; }
            set { this.m_ReplyString = value; }
        }
        private int m_ReplyCode;
        public int ReplyCode
        {
            get { return this.m_ReplyCode; }
            set { this.m_ReplyCode = value; }
        }

        private Encoding m_EncodeType = Encoding.Default;
        /// <summary>
        /// 編碼方式
        /// </summary>
        public Encoding EncodeType
        {
            get { return this.m_EncodeType; }
            set { this.m_EncodeType = value; }
        }
        /// <summary>
        /// 接收和發送數據的緩衝區
        /// </summary>
        private static int BLOCK_SIZE = 512;
        /// <summary>
        /// 緩衝區大小
        /// </summary>
        private Byte[] m_Buffer;
        public Byte[] Buffer
        {
            get { return this.m_Buffer; }
            set { this.m_Buffer = value; }
        }
        /// <summary>
        /// 傳輸模式
        /// </summary>
        private TransferType trType;
        #endregion

        #region 文件路徑配置
        public string localFolder;
        public string remotingFolder;
        #endregion

        #region 連接socket 和 數據socket
        private Socket socketControl;
        public FTPClient()
        {

            strServerIP = "10.10.10.10";
            serverPort = 21;
            strUserID = "iamge";
            strPassword = "123456";
            strRemotePath = "";
            isConnected = false;
            localFolder = @"D:\3.Source\002_FTPTool\imageDebugPath";
            remotingFolder = "/CSW/AntonyShare/";
        }

        public ExecutionResult Connect()
        {
            ExecutionResult exeResult = new ExecutionResult();
            if (!isConnected)
            {
                DisConnect();
                m_Buffer = new Byte[BLOCK_SIZE];
                try
                {
                    socketControl = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    IPEndPoint ep = new IPEndPoint(IPAddress.Parse(strServerIP), serverPort);
                    socketControl.Connect(ep);
                }
                catch //(Exception)
                {
                    exeResult.Message = $"Couldn't connect to remote server {strServerIP}";
                    return exeResult;
                }

                ReadReply();
                if (m_ReplyCode != 220)
                {
                    DisConnect();
                    //throw new IOException(m_ReplyString.Substring(4));
                    try
                    {
                        exeResult.Message = m_ReplyString.Substring(4);
                    }
                    catch
                    {
                        exeResult.Message = $"No reply from remote server {strServerIP}:{serverPort}!";
                    }


                    return exeResult;
                }

                this.SendCommand("USER " + strUserID);
                if (!(m_ReplyCode == 331 || m_ReplyCode == 230))
                {
                    this.CloseSocketConnect();//關閉連接
                    //throw new IOException(m_ReplyString.Substring(4));
                    exeResult.Message = m_ReplyString.Substring(4);
                    return exeResult;
                }
                if (m_ReplyCode != 230)
                {
                    this.SendCommand("PASS " + strPassword);
                    if (!(m_ReplyCode == 230 || m_ReplyCode == 202))
                    {
                        this.CloseSocketConnect();//關閉連接
                        //throw new IOException(m_ReplyString.Substring(4));
                        exeResult.Message = m_ReplyString.Substring(4);
                        return exeResult;
                    }
                }
                isConnected = true;
                exeResult.Status = true;
                exeResult.Message = $"connect server {strServerIP} successfully!";
            }
            return exeResult;
        }
        public void DisConnect()
        {
            if (isConnected && socketControl != null)
            {
                this.SendCommand("QUIT");
            }
            this.CloseSocketConnect();
            this.m_Buffer = null;

        }

        /// <summary>
        /// 關閉socket連接(用於登錄以前)
        /// </summary>
        private void CloseSocketConnect()
        {
            if (this.socketControl != null && this.socketControl.Connected)
            {
                this.socketControl.Close();
                this.socketControl = null;
            }
            this.isConnected = false;
        }

        #region 發送命令
        /// <summary>
        /// 發送命令並獲取應答碼和最後一行應答字符串
        /// </summary>
        /// <param name="strCommand">命令</param>
        public void SendCommand(string strCommand)
        {
            if (this.socketControl == null)
                throw (new Exception("請先連接服務器再進行操作!"));
            Byte[] cmdBytes = m_EncodeType.GetBytes((strCommand + "\r\n").ToCharArray());

          
            /*這段代碼用來清空所有接收*/
            if (!strCommand.Equals(""))
            {
                int n = 0;
                this.socketControl.Send(cmdBytes, cmdBytes.Length, 0);
                this.ReadReply();
                //while (true)
                //{
                //    try
                //    {
                //        this.ReadReply();
                //        if ((!this.ReplyCode.Equals("226")) || (n > 0))
                //        {
                //            break;
                //        }
                //    }
                //    catch (SocketException) { break; }
                //}
            }
            else
            {/*命令爲空,則超時接收,保證接收緩衝區爲空,保證下次接收,一般最爲LIST命令後,接收226代碼使用*/
                int tm = this.socketControl.ReceiveTimeout;
                this.socketControl.ReceiveTimeout = 10;
                while (true)
                {
                    try
                    {
                        int iBytes = this.socketControl.Receive(m_Buffer, m_Buffer.Length, 0);
                        string msg = m_EncodeType.GetString(m_Buffer, 0, iBytes);
                        int reply_code = Int32.Parse(msg.Substring(0, 3));

                        if (226 == reply_code)
                            break;
                    }
                    catch (SocketException)
                    {
                        break;
                    }
                }
                this.socketControl.ReceiveTimeout = tm;
            }
        }
        #endregion

        private Socket CreateDataSocket()
        {
            SendCommand("PASV");
            if (ReplyCode != 227)
            {
                throw new IOException(m_ReplyString.Substring(4));
            }
            int index1 = m_ReplyString.IndexOf('(');
            int index2 = m_ReplyString.IndexOf(')');
            string ipData =
            m_ReplyString.Substring(index1 + 1, index2 - index1 - 1);
            int[] parts = new int[6];
            int len = ipData.Length;
            int partCount = 0;
            string buf = "";
            for (int i = 0; i < len && partCount <= 6; i++)
            {
                char ch = Char.Parse(ipData.Substring(i, 1));
                if (Char.IsDigit(ch))
                    buf += ch;
                else if (ch != ',')
                {
                    throw new IOException("Malformed PASV m_ReplyString: " +
                    m_ReplyString);
                }
                if (ch == ',' || i + 1 == len)
                {
                    try
                    {
                        parts[partCount++] = Int32.Parse(buf);
                        buf = "";
                    }
                    catch (Exception)
                    {
                        throw new IOException("Malformed PASV m_ReplyString: " +
                        m_ReplyString);
                    }
                }
            }
            string ipAddress = parts[0] + "." + parts[1] + "." +
            parts[2] + "." + parts[3];
            int port = (parts[4] << 8) + parts[5];
            Socket s = new
            Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ep = new
            IPEndPoint(IPAddress.Parse(ipAddress), port);
            try
            {
                s.Connect(ep);
            }
            catch (Exception)
            {
                throw new IOException("Can't connect to remote server");
            }
            return s;
        }
        #endregion

        #region 文件操作
        public string CreateFolder()
        {
            string folder = localFolder + "\\" + DateTime.Now.ToString("yyyy_MM_dd");//
            if (!Directory.Exists(folder))
                Directory.CreateDirectory(folder);
            return folder;
        }

        //public string[] Dir(string strMask)
        public ExecutionResult Dir(string strMask)
        {
            ExecutionResult exeResult = new ExecutionResult();

            //建立鏈接
            if (!isConnected)
            {
                exeResult = Connect();
                if (!exeResult.Status)
                {
                    return exeResult;
                }
            }
            //建立進行數據連接的socket
            Socket socketData = CreateDataSocket();
            //傳送命令
            SendCommand("LIST " + strMask);

            //分析應答代碼

            if (!(ReplyCode == 150 || ReplyCode == 125 || ReplyCode == 226))
            {
                //throw new IOException(ReplyString.Substring(4));
                exeResult.Message = m_ReplyString.Substring(4);
                return exeResult;
            }

            //獲得結果
            string strMsg = "";
            while (true)
            {
                int iBytes = socketData.Receive(m_Buffer, m_Buffer.Length, 0);
                //strMsg += Encoding.GB2312.GetString(m_Buffer, 0, iBytes);
                strMsg += Encoding.Default.GetString(m_Buffer, 0, iBytes);
                if (iBytes < m_Buffer.Length)
                {
                    break;
                }
            }
            char[] seperator = { '\n' };
            string[] strsFileList = strMsg.Split(seperator);
            socketData.Close();//數據socket關閉時也會有返回碼 
            if (ReplyCode != 226)
            {
                ReadReply();
                if (ReplyCode != 226)
                {
                    //throw new IOException(m_ReplyString.Substring(4));
                    exeResult.Message = m_ReplyString.Substring(4);
                    return exeResult;
                }
            }
            exeResult.Anything = strsFileList;
            exeResult.Status = true;
            return exeResult;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileMark">*</param>
        /// <param name="path"></param>
        /// <param name="folder"></param>
        /// <returns></returns>
        public ExecutionResult GetFolder(string fileMark, string path, string folder)
        {
            ExecutionResult exeResult = new ExecutionResult();
            exeResult = Dir(path);
            if (!exeResult.Status)
            {
                exeResult.Message = "";
                return exeResult;
            }
            string[] dirs = (string[])exeResult.Anything;  //獲取目錄下的內容 

            ChDir(path);  //改變目錄 
            foreach (string dir in dirs)
            {
                string[] infos = dir.Split(' ');
                string info = infos[infos.Length - 1].Replace("\r", "");
                //if (dir.StartsWith("d") && !string.IsNullOrEmpty(dir))  //爲目錄
                //{
                //    if (!info.EndsWith(".") && !info.EndsWith(".."))  //篩選出真實的目錄 
                //    {
                //        Directory.CreateDirectory(folder + "//" + info);
                //        GetFolder(fileMark, path + "/" + info, folder + "//" + info);
                //        ChDir(path);
                //    }
                //}
                //else 
                if (dir.StartsWith("-r"))  //爲文件 
                {
                    string file = folder + "\\" + info;
                    if (File.Exists(file))
                    {
                        long remotingSize = GetFileSize(info);
                        FileInfo fileInfo = new FileInfo(file);
                        long localSize = fileInfo.Length;

                        if (remotingSize != localSize)  //斷點續傳 
                        {
                            GetBrokenFile(info, folder, info, localSize);
                        }
                    }
                    else
                    {
                        Info($"start downloading {folder}\\{info}");
                        //System.Threading.Thread.Sleep(50);
                        GetFile(info, folder, info);  //下載文件
                        //System.Threading.Thread.Sleep(50);
                        Info("The file "  + info + " has been downloaded");
                    }
                }
            }
            exeResult.Status = true;
            exeResult.Message = "The image has been updated successfully!";
            return exeResult;
        }

        public long GetFileSize(string strFileName)
        {
            if (!isConnected)
            {
                Connect();
            }
            SendCommand("SIZE " + Path.GetFileName(strFileName));
            long lSize = 0;
            if (ReplyCode == 213)
            {
                lSize = Int64.Parse(m_ReplyString.Substring(4));
            }
            else
            {
                throw new IOException(m_ReplyString.Substring(4));
            }
            return lSize;
        }


        public void ChDir(string strDirName)
        {
            if (strDirName.Equals(".") || strDirName.Equals(""))
            {
                return;
            }
            if (!isConnected)
            {
                Connect();
            }
            SendCommand("CWD " + strDirName);
            if (ReplyCode != 250)
            {
                throw new IOException(m_ReplyString.Substring(4));
            }
            this.strRemotePath = strDirName;
        }

        /// 傳輸模式:二進制類型、ASCII類型 
        public enum TransferType
        {
            Binary,
            ASCII
        };

        /// 設置傳輸模式 
        /// 傳輸模式
        public void SetTransferType(TransferType ttType)
        {
            if (ttType == TransferType.Binary)
            {
                SendCommand("TYPE I");//binary類型傳輸 
            }
            else
            {
                SendCommand("TYPE A");//ASCII類型傳輸 
            }
            if (ReplyCode != 200)
            {
                throw new IOException(m_ReplyString.Substring(4));
            }
            else
            {
                trType = ttType;
            }
        }

        /// 下載一個文件                
        /// 要下載的文件名 
        /// 本地目錄(不得以/結束)
        /// 保存在本地時的文件名
        public void GetFile(string strRemoteFileName, string strFolder, string strLocalFileName)
        {
            if (!isConnected)
            {
                Connect();
            }
            SetTransferType(TransferType.Binary);
            if (strLocalFileName.Equals(""))
            {
                strLocalFileName = strRemoteFileName;
            }
            if (!File.Exists(strLocalFileName))
            {
                Stream st = File.Create(strLocalFileName);
                st.Close();
            }

            FileStream output = new FileStream(strFolder + "//" + strLocalFileName, FileMode.Create);
            Socket socketData = CreateDataSocket();
            SendCommand("RETR " + strRemoteFileName);
            if (!(ReplyCode == 150 || ReplyCode == 125
            || ReplyCode == 226 || ReplyCode == 250))
            {
                Info(m_ReplyString.Substring(4));
                throw new IOException(m_ReplyString.Substring(4));
            }
            while (true)
            {
                int iBytes = socketData.Receive(m_Buffer, m_Buffer.Length, 0);
                output.Write(m_Buffer, 0, iBytes);
                if (iBytes <= 0)
                {
                    break;
                }
            }
            output.Close();
            if (socketData.Connected)
            {
                socketData.Close();
            }
            if (!(ReplyCode == 226 || ReplyCode == 250))
            {
                ReadReply();
                if (!(ReplyCode == 226 || ReplyCode == 250))
                {
                    Info(m_ReplyString.Substring(4));
                    throw new IOException(m_ReplyString.Substring(4));
                }
            }
        }

        /*/// 
        /// 下載一個文件 
        / 要下載的文件名 
        / 本地目錄(不得以/結束)
        / 保存在本地時的文件名*/
        public void GetBrokenFile(string strRemoteFileName, string strFolder, string strLocalFileName, long size)
        {
            if (!isConnected)
            {
                Connect();
            }
            SetTransferType(TransferType.Binary);

            FileStream output = new
            FileStream(strFolder + "//" + strLocalFileName, FileMode.Append);
            Socket socketData = CreateDataSocket();
            SendCommand("REST " + size.ToString());
            SendCommand("RETR " + strRemoteFileName);
            if (!(ReplyCode == 150 || ReplyCode == 125
            || ReplyCode == 226 || ReplyCode == 250))
            {
                throw new IOException(m_ReplyString.Substring(4));
            }

            int byteYu = (int)size % 512;
            int byteChu = (int)size / 512;
            byte[] tempBuffer = new byte[byteYu];
            for (int i = 0; i < byteChu; i++)
            {
                socketData.Receive(m_Buffer, m_Buffer.Length, 0);
            }
            socketData.Receive(tempBuffer, tempBuffer.Length, 0);

            socketData.Receive(m_Buffer, byteYu, 0);

            int totalBytes = 0;//added
            while (true)
            {
                int iBytes = socketData.Receive(m_Buffer, m_Buffer.Length, 0);
                totalBytes += iBytes;
                output.Write(m_Buffer, 0, iBytes);
                if (iBytes <= 0)
                {
                    break;
                }
            }
            output.Close();
            if (socketData.Connected)
            {
                socketData.Close();
            }
            if (!(ReplyCode == 226 || ReplyCode == 250))
            {
                ReadReply();
                if (!(ReplyCode == 226 || ReplyCode == 250))
                {
                    throw new IOException(m_ReplyString.Substring(4));
                }
            }
        }


        #endregion

        #region 讀取應答代碼
        /// <summary>
        /// 將一行應答字符串記錄在m_ReplyString和strMsg
        /// 應答碼記錄在ReplyCode
        /// </summary>

        /// <summary>
        /// 讀取最後一行的消息
        /// 讀取Socket返回的所有字符串
        /// </summary>
        /// <returns>包含應答碼的字符串行</returns>
        private string ReadLine()
        {
            if (socketControl == null)
                throw (new Exception("請先連接服務器再進行操作!"));
            while (true)
            {
                int iBytes = socketControl.Receive(m_Buffer, m_Buffer.Length, 0);
                m_Message += m_EncodeType.GetString(m_Buffer, 0, iBytes);
                if (iBytes < m_Buffer.Length)
                {
                    break;
                }
            }
            char[] seperator = { '\n' };
            string[] mess = m_Message.Split(seperator);
            if (m_Message.Length > 2)
            {
                m_Message = mess[mess.Length - 2];
                //seperator[0]是10,換行符是由13和0組成的,分隔後10後面雖沒有字符串,
                //但也會分配爲空字符串給後面(也是最後一個)字符串數組,
                //所以最後一個mess是沒用的空字符串
                //但爲什麼不直接取mess[0],因爲只有最後一行字符串應答碼與信息之間有空格
            }
            else
            {
                m_Message = mess[0];
                if(m_Message=="")
                {
                    return Message;
                }
            }
            if (!m_Message.Substring(3, 1).Equals(" "))//返回字符串正確的是以應答碼(如220開頭,後面接一空格,再接問候字符串)
            {
                return this.ReadLine();
            }
            return m_Message;
        }

        public void ReadReply()
        {

            try
            {
                this.m_Message = "";
                this.m_ReplyString = this.ReadLine();
                this.m_ReplyCode = Int32.Parse(m_ReplyString.Substring(0, 3));
            }
            catch
            {

            }

        }
    #endregion

        #region events
        public event Action<string> OnInfoEvent;
        public void Info(string log)
        {
            OnInfoEvent?.Invoke(log);
        }
        #endregion
    }
}


///main中 TCP Client 類庫 的使用

FTPClient ftpClient;

private void button3_Click(object sender, EventArgs e)
        {
            ExecutionResult exeResult=ftpClient.GetFolder("*", ftpClient.remotingFolder,     ftpClient.CreateFolder());
            if(exeResult.Status)
            {
                Info(exeResult.Message);
            }
            else
            {
                Error(exeResult.Message);
            }
        }

 

發佈了48 篇原創文章 · 獲贊 42 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章