FTP的文档上传,下载,删除功能的实现

FTP的文档上传功能实现

     public object UploadFile(String filename, string targetDir, string hostname, string username, string password)
        {
            object resObj;
            string URL= hostname + "/" + targetDir;
            FtpWebRequest reqFTP;
            // 根据uri创建FtpWebRequest对象   
            reqFTP =  GetRequest(URL, username, password); ;//CreateFtpWebRequest(ftpPath + "/" + fileName);
            // 在一个命令之后被执行  
            reqFTP.KeepAlive = false;
            reqFTP.UsePassive = true;
            // 指定执行什么命令  
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            reqFTP.Timeout = 120000;
            // 指定数据传输类型  
            reqFTP.UseBinary = true;
            // 上传文件时通知服务器文件的大小  
            FileInfo fileinfo =new FileInfo(filename);
            reqFTP.ContentLength = fileinfo.Length;
            // 缓冲大小设置为2kb  
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            Stream strm=null;
            FileStream fs=null;
            try
            {
                // 把上传的文件写入流  
                using (strm = reqFTP.GetRequestStream())
                {
                    // 打开一个文件流 (System.IO.FileStream) 去读上传的文件  
                    using (fs = fileinfo.OpenRead())//fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    { // 每次读文件流的2kb  
                        contentLen = fs.Read(buff, 0, buffLength);
                        // 流内容没有结束  
                        while (contentLen != 0)
                        {
                            // 把内容从file stream 写入 upload stream  
                            strm.Write(buff, 0, contentLen);
                            contentLen = fs.Read(buff, 0, buffLength);
                        }
                    }
                    resObj = new object[] { 0, "Upload Success!" };
                }
            }
            catch (Exception ex)
            {
                resObj = new object[] { 1, "Upload error:" + ex};
            }
            finally
            {
                if (strm != null)
                    strm.Close();
                if (fs != null)
                    fs.Close();
            }
            return resObj;
        } 

 FTP的文档下载功能实现

  /// <summary>
        /// 將FTP server上的文件下載至本地
        /// </summary>
        /// <param name="vLocalDir">下載至本地路徑</param>
        /// <param name="vFTPDir">FTP目標文件路徑</param>
        /// <param name="vFTPFile">從ftp要下載的文件名</param>
        /// <param name="vUID">登錄FTP用戶名</param>
        /// <param name="vPassword">登錄FTP密碼</param>
        public object DownloadFile(string vLocalDir, string vFTPDir, string vFTPFile, string vUID, string vPassword)
        {
            object resObj;
            System.Net.FtpWebRequest ftp;
            string vURI = vFTPDir + "/" + vFTPFile;
            string ftpBakPath = vFTPDir + "/bak";
            string tmpFileName = Guid.NewGuid().ToString();
            string localFile = vLocalDir + tmpFileName;
            ftp = GetRequest(vURI, vUID, vPassword);
            ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
            ftp.UseBinary = true;
            ftp.UsePassive = false;
            ftp.Timeout = 120000;

            try
            {
                using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        //loop to read & write to file
                        using (FileStream fs = new FileStream(localFile, FileMode.CreateNew))
                        {
                            try
                            {
                                byte[] buffer = new byte[2048];
                                int read = 0;
                                do
                                {
                                    read = responseStream.Read(buffer, 0, buffer.Length);
                                    fs.Write(buffer, 0, read);
                                } while (!(read == 0));
                                responseStream.Close();
                                fs.Flush();
                                fs.Close();
                            }
                            catch (Exception)
                            {
                                //catch error and delete file only partially downloaded
                                fs.Close();
                                //delete target file as it's incomplete
                                File.Delete(localFile);
                                throw;
                            }
                            fs.Close();
                        }
                        responseStream.Close();
                    }
                    response.Close();
                }
                File.Delete(vLocalDir + vFTPFile);//delete 本機路徑下的文檔
                File.Move(localFile, vLocalDir + vFTPFile);//相當於給文件重命名.
                resObj = new object[] { 0, "Download Success!" };
            }
            catch (Exception ex)
            {
                File.Delete(localFile);
                resObj = new object[] { 1, "Download file error:" + ex.Message };
            }
            ftp = null;
            return resObj;
        } 

FTP的文档删除功能实现 

  /// <summary>
        /// 刪除FTPserver上的文件
        /// </summary>
        /// <param name="vFTPDir">FTP目標文件路徑</param>
        /// <param name="vUID">登錄FTP用戶名</param>
        /// <param name="vPassword">登錄FTP密碼</param>
        /// <param name="vFileName">FTP上要刪除的文件名</param>
        public object DeleteFTPFile(string vFTPDir, string vUID, string vPassword, string vFileName)
        {
            object resObj;
            System.Net.FtpWebRequest ftp;
            string vURI = vFTPDir + "/" + vFileName;
            ftp = GetRequest(vURI, vUID, vPassword);
            ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile;
            ftp.UseBinary = true;
            ftp.UsePassive = false;
            ftp.Timeout = 120000;
            try
            {
                string result = String.Empty;
                FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
                long size = response.ContentLength;
                Stream datastream = response.GetResponseStream();
                StreamReader sr = new StreamReader(datastream);
                result = sr.ReadToEnd();
                sr.Close();
                datastream.Close();
                response.Close();
                resObj = new object[] { 0, "Delete Success!" };
            }
            catch (Exception ex)
            {
                resObj = new object[] { 1, "Delete file error:" + ex.Message};
            }
            ftp = null;
            return resObj;
        } 

FTP共用调用方法:

   /// <summary>
        /// 創建FTP連接
        /// </summary>
        /// <param name="vURI">FTP路徑</param>
        /// <param name="vUID">登錄FTP用戶名</param>
        /// <param name="vPassword">登錄FTP密碼</param>
        private static FtpWebRequest GetRequest(string vURI, string vUID, string vPassword)
        {
            //根據服務器信息FtpWebRequest創建類的對象
            FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(new Uri(vURI));
            //提供身份驗證信息
            result.Credentials = new System.Net.NetworkCredential(vUID, vPassword);
            //設置請求完成之後是否保持到ftp服務器的控制連接,默認值為true
            //result.KeepAlive = false;
            return result;
        } 
posted @ 2021-05-04 15:25  码农阿亮  阅读(333)  评论(0编辑  收藏  举报