【.NET】FTP

namespace Test.FTP
{
    public class MyFtp
    {
        private bool _isKeepAlive;
        private string _password;
        private string _serverIp;
        private string _userId;
        private int bufferSize;
        private FtpWebRequest ftpRequest;
        private FtpWebResponse ftpResponse;
        private Stream ftpStream;


        public MyFtp(string ftpServerIp, string ftpUserId, string ftpPassWord)
        {
            this.ftpRequest = null;
            this.ftpResponse = null;
            this.ftpStream = null;
            this.bufferSize = 0x800;
            this._serverIp = ftpServerIp;
            this._password = ftpPassWord;
            this._userId = ftpUserId;
            this._isKeepAlive = false;
        }

        public MyFtp(string ftpServerIp, string ftpUserId, string ftpPassWord, bool isKeepAlive)
        {
            this.ftpRequest = null;
            this.ftpResponse = null;
            this.ftpStream = null;
            this.bufferSize = 0x800;
            this._serverIp = ftpServerIp;
            this._password = ftpPassWord;
            this._userId = ftpUserId;
            this._isKeepAlive = isKeepAlive;
        }


        private void Connect()
        {
            this.ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + this._serverIp));
            this.ftpRequest.UseBinary = true;
            this.ftpRequest.UsePassive = true;
            this.ftpRequest.KeepAlive = _isKeepAlive;
            this.ftpRequest.Credentials = new NetworkCredential(this._userId, this._password);
        }

        private void Connect(string path)
        {
            this.ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(path));
            this.ftpRequest.UseBinary = true;
            this.ftpRequest.UsePassive = true;
            this.ftpRequest.KeepAlive = _isKeepAlive;
            this.ftpRequest.Credentials = new NetworkCredential(this._userId, this._password);
        }

        /// <summary>
        /// 创建目录
        /// </summary>
        /// <param name="dirName"></param>
        /// <returns></returns>
        public bool CreateDirectory(string dirName)
        {
            try
            {
                this.Connect("ftp://" + this._serverIp + "/" + dirName);
                this.ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
                this.ftpResponse = (FtpWebResponse)this.ftpRequest.GetResponse();
                this.ftpResponse.Close();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="deleteFile"></param>
        /// <returns></returns>
        public bool Delete(string deleteFile)
        {
            try
            {
                this.Connect("ftp://" + this._serverIp + "/" + deleteFile);
                this.ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
                this.ftpResponse = (FtpWebResponse)this.ftpRequest.GetResponse();
                this.ftpResponse.Close();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 删除目录
        /// </summary>
        /// <param name="dirName"></param>
        /// <returns></returns>
        public bool DeleteDirectory(string dirName)
        {
            try
            {
                this.Connect("ftp://" + this._serverIp + "/" + dirName);
                this.ftpRequest.Method = WebRequestMethods.Ftp.RemoveDirectory;
                this.ftpResponse = (FtpWebResponse)this.ftpRequest.GetResponse();
                this.ftpResponse.Close();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="remoteFile"></param>
        /// <param name="LocalFile"></param>
        /// <returns></returns>
        public bool DownLoad(string remoteFile, string LocalFile)
        {
            bool isSuccess;
            try
            {
                this.DownLoadContent(remoteFile, LocalFile);
                isSuccess = true;
            }
            catch (Exception)
            {
                try
                {
                    this.DownLoadContent(remoteFile, LocalFile);
                    isSuccess = true;
                }
                catch (Exception)
                {
                    isSuccess = false;
                }
            }

            return isSuccess;
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="remoteFile"></param>
        /// <param name="LocalFile"></param>
        /// <returns></returns>
        public bool UpLoad(string remoteFile, string LocalFile)
        {
            bool isSuccess;
            try
            {
                this.UploadContent(remoteFile, LocalFile);
                isSuccess = true;
            }
            catch (Exception)
            {
                try
                {
                    this.UploadContent(remoteFile, LocalFile);
                    isSuccess = true;
                }
                catch (Exception)
                {
                    isSuccess = false;
                }
            }

            return isSuccess;
        }


        public string[] GetSimpleFileList(string remoteFile)
        {
            try
            {
                this.Connect("ftp://" + this._serverIp + "/" + remoteFile);

                StringBuilder sb = new StringBuilder();
                this.ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;

                this.ftpResponse = (FtpWebResponse)this.ftpRequest.GetResponse();
                this.ftpStream = this.ftpResponse.GetResponseStream();

                StreamReader ftpReader = new StreamReader(ftpStream);

                try
                {
                    while (ftpReader.Peek() != -1)
                    {
                        sb.Append(ftpReader.ReadLine());
                        sb.Append("|");
                    }
                }
                catch (Exception ex)
                {
                    Console.Write(ex.ToString());
                }

                ftpReader.Close();
                this.ftpStream.Close();
                this.ftpResponse.Close();
                return sb.ToString().Split(new char[] { ‘|‘ });
            }

            catch (Exception EX)
            {
                Console.WriteLine(EX.ToString());
                return null;
            }
        }

        private void DownLoadContent(string remoteFile, string localFile)
        {
            this.Connect("ftp://" + this._serverIp + "/" + remoteFile);
            this.ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
            using (this.ftpResponse = (FtpWebResponse)this.ftpRequest.GetResponse())
            {
                using (this.ftpStream = this.ftpResponse.GetResponseStream())
                {
                    this.ftpStream.ReadTimeout = 0x1d4c0;
                    using (FileStream localStream = new FileStream(localFile, FileMode.Create))
                    {
                        byte[] buffer = new byte[this.bufferSize];
                        for (int bytesRead = this.ftpStream.Read(buffer, 0, this.bufferSize); bytesRead > 0; bytesRead = this.ftpStream.Read(buffer, 0, this.bufferSize))
                        {
                            localStream.Write(buffer, 0, bytesRead);
                        }
                    }

                }
            }
        }

        private void UploadContent(string remoteFile, string localFile)
        {
            FileInfo fileInfo = new FileInfo(localFile);
            this.Connect("ftp://" + this._serverIp + "/" + remoteFile);
            this.ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
            this.ftpRequest.ContentLength = fileInfo.Length;

            using (FileStream stream = fileInfo.OpenRead())
            {
                byte[] byteBuffer = new byte[this.bufferSize];

                int contentLen = 0;
                using (this.ftpStream = this.ftpRequest.GetRequestStream())
                {
                    for (contentLen = stream.Read(byteBuffer, 0, this.bufferSize); contentLen != 0; contentLen = stream.Read(byteBuffer, 0, bufferSize))
                    {
                        this.ftpStream.Write(byteBuffer, 0, contentLen);
                    }
                }
            }
        }

        /// <summary>
        /// 重命名文件
        /// </summary>
        /// <param name="currentFileNameAndPath"></param>
        /// <param name="newFileName"></param>
        /// <returns></returns>
        public bool Rename(string currentFileNameAndPath, string newFileName)
        {
            try
            {
                this.Connect("ftp://" + this._serverIp + "/" + currentFileNameAndPath);
                this.ftpRequest.Method = WebRequestMethods.Ftp.Rename;
                this.ftpRequest.RenameTo = "/" + newFileName;
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                this.ftpResponse.Close();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return false;
            }
        }
    }
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。