天天看点

C# FTPHelper工具类

/// <summary>
    /// Ftp
    /// </summary>
    public class FtpFileOperation
    {
        private string _ftpIp;
        private string _ftpUser;
        private string _ftpPassword;
        private FtpWebRequest _ftpWebRequest;

        public FtpFileOperation(string ftpIp, string ftpUser, string ftpPassword)
        {
            _ftpIp = ftpIp;
            _ftpUser = ftpUser;
            _ftpPassword = ftpPassword;
        }

        /// <summary>
        /// Connect
        /// </summary>
        /// <param name="ftpUrl"></param>
        /// <returns></returns>
        public bool Connect(string ftpUrl)
        {
            try
            {
                _ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(ftpUrl);
                _ftpWebRequest.UseBinary = true;
                _ftpWebRequest.Credentials = new NetworkCredential(_ftpUser, _ftpPassword);
                return true;
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return false;
            }
        }

        /// <summary>
        /// Download
        /// </summary>
        /// <param name="ftpFilePath"></param>
        /// <param name="savePath"></param>
        /// <returns></returns>
        public bool Download(string ftpFilePath,string savePath)
        {
            try
            {
                if (Connect(String.Format("ftp://{0}/{1}", _ftpIp, ftpFilePath)))
                {
                    FtpWebResponse ftpResponse = (FtpWebResponse)_ftpWebRequest.GetResponse();
                    Stream ftpStream = ftpResponse.GetResponseStream();
                    byte[] buffer = new byte[2048];
                    int readCount = 0;
                    FileStream outputStream = new FileStream(savePath, FileMode.Create);
                    readCount = ftpStream.Read(buffer, 0, buffer.Length);
                    while(readCount > 0)
                    {
                        outputStream.Write(buffer, 0, readCount);
                        readCount = ftpStream.Read(buffer, 0, buffer.Length);
                    }
                    ftpStream.Close();
                    outputStream.Close();
                    ftpResponse.Close();
                    return true;
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
            return false;
        }
    }