用于同步服务器文件的一款FTPS 客户端工具开发

因生产需要,开发一款工具用于同步服务器端的文件,为了避免产线员工由于误操作拷贝错文件的情况出现。其开发过程记录如下:

1.先下载FTP Server

FileZilla_Server-0_9_60_2.7z-C#文档类资源-CSDN下载

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);
            }
        }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值