码迷,mamicode.com
首页 > Web开发 > 详细

【.NET】FTP

时间:2014-09-24 14:09:26      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:blog   io   os   ar   for   文件   div   sp   on   

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

 

【.NET】FTP

标签:blog   io   os   ar   for   文件   div   sp   on   

原文地址:http://www.cnblogs.com/wywnet/p/3990055.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!