ftp上傳文件和下載文件


 

    public class FtpService
    {
        #region Fields and attributes
        private readonly int BufLen = 2048;
        /// <summary>
        /// ftp服務器地址
        /// </summary>
        private readonly string FtpServer = Properties.Settings.Default.FtpServer;
        /// <summary>
        /// ftp用戶名
        /// </summary>
        private readonly string FtpUser = Properties.Settings.Default.user;
        /// <summary>
        /// ftp密碼
        /// </summary>
        private readonly string FtpPassword = Properties.Settings.Default.password;
        #endregion

        #region Events
        /// <summary>
        /// 文件上傳結果
        /// </summary>
        /// <param>true-成功,false-失敗</param>
        /// <param>信息</param>
        public event Action<bool, string> EventUploadResult = null;
        /// <summary>
        /// 文件上傳進度
        /// </summary>
        /// <param>文件已上傳大小</param>
        /// <param>文件總大小</param>
        /// <param>文件名稱</param>
        public event Action<long, long, string> EventUploadFileProgress = null;
        /// <summary>
        /// 所有文件上傳進度
        /// </summary>
        /// <param>文件已上傳數</param>
        /// <param>文件總總數</param>
        public event Action<int, int> EventUploadBatchFilesProgress = null;
        /// <summary>
        /// 文件下載結果
        /// </summary>
        /// <param>true-成功,false-失敗</param>
        /// <param>信息</param>
        public event Action<bool, string> EventDonwloadResult = null;
        /// <summary>
        /// 文件下載進度
        /// </summary>
        /// <param>文件已下載大小</param>
        /// <param>文件總大小</param>
        /// <param>文件名稱</param>
        public event Action<long, long, string> EventDonwloadFileProgress = null;
        /// <summary>
        /// 所有文件下載進度
        /// </summary>
        /// <param>文件已下載數</param>
        /// <param>文件總總數</param>
        public event Action<int, int> EventDonwloadBatchFilesProgress = null;
        #endregion

        #region public methods
        /// <summary>
        /// 上傳文件到FTPServer
        /// </summary>
        /// <param name="file"></param>
        public bool UploadFile(string localFilePath)
        {
            if (string.IsNullOrEmpty(localFilePath))
                return false;

            bool ret = true;
            FtpWebRequest reqFtp = null;
            try
            {
                FileInfo localFileInfo = new FileInfo(localFilePath);
                string serverFilePath = $@"{FtpServer}\{ localFileInfo.Name}";

                //FtpWebRequest配置
                reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(serverFilePath));
                reqFtp.UseBinary = true;
                reqFtp.Credentials = new NetworkCredential(FtpUser, FtpPassword); //設置通信憑據
                reqFtp.KeepAlive = false;
                reqFtp.Method = WebRequestMethods.Ftp.UploadFile;
                reqFtp.ContentLength = localFileInfo.Length;

                //讀本地文件數據並上傳
                using (FileStream fileStream = localFileInfo.OpenRead())
                {
                    using (Stream stream = reqFtp.GetRequestStream())
                    {
                        long totalLen = 0;
                        int contentLen = 0;
                        byte[] buff = new byte[BufLen];
                        while ((contentLen = fileStream.Read(buff, 0, BufLen)) > 0)
                        {
                            stream.Write(buff, 0, contentLen);
                            totalLen += contentLen;
                            if (EventUploadFileProgress != null)
                                EventUploadFileProgress(totalLen, localFileInfo.Length, localFileInfo.Name);
                        }
                    }
                }

                ret = true;
                if (EventUploadResult != null)
                    EventUploadResult(ret, $@"{localFilePath} : 上傳成功!");
            }
            catch (Exception ex)
            {
                ret = false;
                if (EventUploadResult != null)
                    EventUploadResult(ret, $@"{localFilePath} : 上傳失敗!Exception : {ex.ToString()}");
            }
            finally
            {
                if (reqFtp != null)
                    reqFtp.Abort();
            }

            return ret;
        }

        /// <summary>
        /// 從FTPServer上下載文件
        /// </summary>
        public bool DownloadFile(string fileName, long length, string localDirectory)
        {
            if (string.IsNullOrEmpty(localDirectory) || string.IsNullOrEmpty(fileName))
                return false;

            bool ret = true;
            FtpWebRequest reqFtp = null;
            FtpWebResponse respFtp = null;
            string localFilePath = $@"{localDirectory}\{fileName}";
            string serverFilePath = $@"{FtpServer}\{fileName}";

            try
            {
                if (File.Exists(localFilePath))
                    File.Delete(localFilePath);

                //建立ftp連接
                reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(serverFilePath));
                reqFtp.UseBinary = true;
                reqFtp.Credentials = new NetworkCredential(FtpUser, FtpPassword);
                reqFtp.KeepAlive = false;
                reqFtp.Method = WebRequestMethods.Ftp.DownloadFile;

                //讀服務器文件數據並寫入本地文件
                respFtp = reqFtp.GetResponse() as FtpWebResponse;
                using (Stream stream = respFtp.GetResponseStream())
                {
                    using (FileStream fileStream = new FileStream(localFilePath, FileMode.Create))
                    {
                        long totalLen = 0;
                        int contentLen = 0;
                        byte[] buff = new byte[BufLen];
                        while ((contentLen = stream.Read(buff, 0, BufLen)) > 0)
                        {
                            fileStream.Write(buff, 0, contentLen);
                            totalLen += contentLen;
                            if (EventDonwloadFileProgress != null && length > 0)
                                EventDonwloadFileProgress(totalLen, length, fileName);
                        }
                    }
                }

                ret = true;
                if (EventDonwloadResult != null)
                    EventDonwloadResult(ret, $@"{serverFilePath} : 下載成功!");
            }
            catch (Exception ex)
            {
                ret = false;
                if (EventDonwloadResult != null)
                    EventDonwloadResult(ret, $@"{serverFilePath} : 下載失敗!Exception : {ex.ToString()}");
            }
            finally
            {
                if (reqFtp != null)
                    reqFtp.Abort();
                if (respFtp != null)
                    respFtp.Close();
            }

            return ret;
        }

        /// <summary>
        /// 批量上傳文件
        /// </summary>
        /// <param name="localFilePaths"></param>
        public void UploadFiles(List<string> localFilePaths)
        {
            if (localFilePaths == null || localFilePaths.Count == 0)
                return;

            int i = 1;
            foreach (var localFilePath in localFilePaths)
            {
                UploadFile(localFilePath);
                if (EventUploadBatchFilesProgress != null)
                    EventUploadBatchFilesProgress(i++, localFilePaths.Count);
            }
        }

        /// <summary>
        /// 批量下載文件
        /// </summary>
        /// <param name="fileNames"></param>
        /// <param name="localDirectory"></param>
        public void DownloadFiles(List<FileModel> files, string localDirectory)
        {
            if (files == null || files.Count == 0 || string.IsNullOrEmpty(localDirectory))
                return;

            int i = 1;
            foreach (var file in files)
            {
                DownloadFile(file.Name, file.Size, localDirectory);
                if (EventDonwloadBatchFilesProgress != null)
                    EventDonwloadBatchFilesProgress(i++, files.Count);
            }
        }

        /// <summary>
        /// 異步上傳文件到FTPServer
        /// </summary>
        /// <param name="file"></param>
        public async Task<bool> UploadFileAsync(string localFilePath)
        {
            if (string.IsNullOrEmpty(localFilePath))
                return false;

            bool ret = true;
            FtpWebRequest reqFtp = null;
            try
            {
                FileInfo localFileInfo = new FileInfo(localFilePath);
                string serverFilePath = $@"{FtpServer}\{ localFileInfo.Name}";

                //FtpWebRequest配置
                reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(serverFilePath));
                reqFtp.UseBinary = true;
                reqFtp.Credentials = new NetworkCredential(FtpUser, FtpPassword); //設置通信憑據
                reqFtp.KeepAlive = false;
                reqFtp.Method = WebRequestMethods.Ftp.UploadFile;
                reqFtp.ContentLength = localFileInfo.Length;

                //讀本地文件數據並上傳
                using (FileStream fileStream = localFileInfo.OpenRead())
                {
                    using (Stream stream = await reqFtp.GetRequestStreamAsync())
                    {
                        long totalLen = 0;
                        int contentLen = 0;
                        byte[] buff = new byte[BufLen];
                        while ((contentLen = await fileStream.ReadAsync(buff, 0, BufLen)) > 0)
                        {
                            await stream.WriteAsync(buff, 0, contentLen);
                            totalLen += contentLen;
                            if (EventUploadFileProgress != null)
                                EventUploadFileProgress(totalLen, localFileInfo.Length, localFileInfo.Name);
                        }
                    }
                }

                ret = true;
                if (EventUploadResult != null)
                    EventUploadResult(ret, $@"{localFilePath} : 上傳成功!");
            }
            catch (Exception ex)
            {
                ret = false;
                if (EventUploadResult != null)
                    EventUploadResult(ret, $@"{localFilePath} : 上傳失敗!Exception : {ex.ToString()}");
            }
            finally
            {
                if (reqFtp != null)
                    reqFtp.Abort();
            }

            return ret;
        }

        /// <summary>
        /// 異步從FTPServer上下載文件
        /// </summary>
        public async Task<bool> DownloadFileAsync(string fileName, long length, string localDirectory)
        {
            if (string.IsNullOrEmpty(localDirectory) || string.IsNullOrEmpty(fileName))
                return false;

            bool ret = true;
            FtpWebRequest reqFtp = null;
            FtpWebResponse respFtp = null;
            string localFilePath = $@"{localDirectory}\{fileName}";
            string serverFilePath = $@"{FtpServer}\{fileName}";

            try
            {
                if (File.Exists(localFilePath))
                    File.Delete(localFilePath);

                //建立ftp連接
                reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(serverFilePath));
                reqFtp.UseBinary = true;
                reqFtp.Credentials = new NetworkCredential(FtpUser, FtpPassword);
                reqFtp.KeepAlive = false;
                reqFtp.Method = WebRequestMethods.Ftp.DownloadFile;

                //讀服務器文件數據並寫入本地文件
                respFtp = await reqFtp.GetResponseAsync() as FtpWebResponse;
                using (Stream stream = respFtp.GetResponseStream())
                {
                    using (FileStream fileStream = new FileStream(localFilePath, FileMode.Create))
                    {
                        long totalLen = 0;
                        int contentLen = 0;
                        byte[] buff = new byte[BufLen];
                        while ((contentLen = await stream.ReadAsync(buff, 0, BufLen)) > 0)
                        {
                            await fileStream.WriteAsync(buff, 0, contentLen);
                            totalLen += contentLen;
                            if (EventDonwloadFileProgress != null && length > 0)
                                EventDonwloadFileProgress(totalLen, length, fileName);
                        }
                    }
                }

                ret = true;
                if (EventDonwloadResult != null)
                    EventDonwloadResult(ret, $@"{serverFilePath} : 下載成功!");
            }
            catch (Exception ex)
            {
                ret = false;
                if (EventDonwloadResult != null)
                    EventDonwloadResult(ret, $@"{serverFilePath} : 下載失敗!Exception : {ex.ToString()}");
            }
            finally
            {
                if (reqFtp != null)
                    reqFtp.Abort();
                if (respFtp != null)
                    respFtp.Close();
            }

            return ret;
        }

        /// <summary>
        /// 異步批量上傳文件
        /// </summary>
        /// <param name="localFilePaths"></param>
        public async void UploadFilesAsync(List<string> localFilePaths)
        {
            if (localFilePaths == null || localFilePaths.Count == 0)
                return;

            int i = 1;
            foreach (var localFilePath in localFilePaths)
            {
                await UploadFileAsync(localFilePath);
                if (EventUploadBatchFilesProgress != null)
                    EventUploadBatchFilesProgress(i++, localFilePaths.Count);
            }
        }

        /// <summary>
        /// 異步批量下載文件
        /// </summary>
        /// <param name="fileNames"></param>
        /// <param name="localDirectory"></param>
        public async void DownloadFilesAsync(List<FileModel> files, string localDirectory)
        {
            if (files == null || files.Count == 0 || string.IsNullOrEmpty(localDirectory))
                return;

            int i = 1;
            foreach (var file in files)
            {
                await DownloadFileAsync(file.Name, file.Size, localDirectory);
                if (EventDonwloadBatchFilesProgress != null)
                    EventDonwloadBatchFilesProgress(i++, files.Count);
                System.Threading.Thread.Sleep(1000);
            }
        }

        /// <summary>
        /// 讀取遠程文件的內容
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public string ReadFromFile(string serverFilePath)
        {
            if (string.IsNullOrEmpty(serverFilePath))
                return "";

            string ret = "";
            FtpWebRequest reqFtp = null;
            FtpWebResponse respFtp = null;

            try
            {
                //建立ftp連接
                reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(serverFilePath));
                reqFtp.UseBinary = true;
                reqFtp.Credentials = new NetworkCredential(FtpUser, FtpPassword);
                reqFtp.KeepAlive = false;
                reqFtp.Method = WebRequestMethods.Ftp.DownloadFile;

                respFtp = reqFtp.GetResponse() as FtpWebResponse;
                using (Stream stream = respFtp.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        ret = reader.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                ret = "";
                throw ex;
            }
            finally
            {
                if (reqFtp != null)
                    reqFtp.Abort();
                if (respFtp != null)
                    respFtp.Close();
            }

            return ret;
        }

        /// <summary>
        /// 讀取遠程文件的內容
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public async Task<string> ReadFromFileAsync(string serverFilePath)
        {
            if (string.IsNullOrEmpty(serverFilePath))
                return "";

            string ret = "";
            FtpWebRequest reqFtp = null;
            FtpWebResponse respFtp = null;

            try
            {
                //建立ftp連接
                reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(serverFilePath));
                reqFtp.UseBinary = true;
                reqFtp.Credentials = new NetworkCredential(FtpUser, FtpPassword);
                reqFtp.KeepAlive = false;
                reqFtp.Method = WebRequestMethods.Ftp.DownloadFile;

                respFtp = reqFtp.GetResponse() as FtpWebResponse;
                using (Stream stream = respFtp.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        ret = await reader.ReadToEndAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                ret = "";
                throw ex;
            }
            finally
            {
                if (reqFtp != null)
                    reqFtp.Abort();
                if (respFtp != null)
                    respFtp.Close();
            }

            return ret;
        }

        #endregion
    }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM