LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

C#FTP操作类:上传下载、断点续传等

admin
2024年1月12日 21:6 本文热度 335
  1. using System;  

  2. using System.Collections.Generic;  

  3. using System.Linq;  

  4. using System.Text;  

  5. using System.Net;  

  6. using System.IO;  

  7.   

  8. namespace JianKunKing.Common.Ftp  

  9. {  

  10.     /// <summary>  

  11.     /// ftp方式文件下载上传  

  12.     /// </summary>  

  13.     public static class FileUpDownload  

  14.     {  

  15.         #region 变量属性  

  16.         /// <summary>  

  17.         /// Ftp服务器ip  

  18.         /// </summary>  

  19.         public static string FtpServerIP = string.Empty;  

  20.         /// <summary>  

  21.         /// Ftp 指定用户名  

  22.         /// </summary>  

  23.         public static string FtpUserID = string.Empty;  

  24.         /// <summary>  

  25.         /// Ftp 指定用户密码  

  26.         /// </summary>  

  27.         public static string FtpPassword = string.Empty;  

  28.  

  29.         #endregion  

  30.  

  31.         #region 从FTP服务器下载文件,指定本地路径和本地文件名  

  32.         /// <summary>  

  33.         /// 从FTP服务器下载文件,指定本地路径和本地文件名  

  34.         /// </summary>  

  35.         /// <param name="remoteFileName">远程文件名</param>  

  36.         /// <param name="localFileName">保存本地的文件名(包含路径)</param>  

  37.         /// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>  

  38.         /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>  

  39.         /// <returns>是否下载成功</returns>  

  40.         public static bool FtpDownload(string remoteFileName, string localFileName, bool ifCredential, Action<int, int> updateProgress = null)  

  41.         {  

  42.             FtpWebRequest reqFTP, ftpsize;  

  43.             Stream ftpStream = null;  

  44.             FtpWebResponse response = null;  

  45.             FileStream outputStream = null;  

  46.             try  

  47.             {  

  48.   

  49.                 outputStream = new FileStream(localFileName, FileMode.Create);  

  50.                 if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)  

  51.                 {  

  52.                     throw new Exception("ftp下载目标服务器地址未设置!");  

  53.                 }  

  54.                 Uri uri = new Uri("ftp://" + FtpServerIP + "/" + remoteFileName);  

  55.                 ftpsize = (FtpWebRequest)FtpWebRequest.Create(uri);  

  56.                 ftpsize.UseBinary = true;  

  57.   

  58.                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);  

  59.                 reqFTP.UseBinary = true;  

  60.                 reqFTP.KeepAlive = false;  

  61.                 if (ifCredential)//使用用户身份认证  

  62.                 {  

  63.                     ftpsize.Credentials = new NetworkCredential(FtpUserID, FtpPassword);  

  64.                     reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);  

  65.                 }  

  66.                 ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;  

  67.                 FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse();  

  68.                 long totalBytes = re.ContentLength;  

  69.                 re.Close();  

  70.   

  71.                 reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;  

  72.                 response = (FtpWebResponse)reqFTP.GetResponse();  

  73.                 ftpStream = response.GetResponseStream();  

  74.   

  75.                 //更新进度    

  76.                 if (updateProgress != null)  

  77.                 {  

  78.                     updateProgress((int)totalBytes, 0);//更新进度条     

  79.                 }  

  80.                 long totalDownloadedByte = 0;  

  81.                 int bufferSize = 2048;  

  82.                 int readCount;  

  83.                 byte[] buffer = new byte[bufferSize];  

  84.                 readCount = ftpStream.Read(buffer, 0, bufferSize);  

  85.                 while (readCount > 0)  

  86.                 {  

  87.                     totalDownloadedByte = readCount + totalDownloadedByte;  

  88.                     outputStream.Write(buffer, 0, readCount);  

  89.                     //更新进度    

  90.                     if (updateProgress != null)  

  91.                     {  

  92.                         updateProgress((int)totalBytes, (int)totalDownloadedByte);//更新进度条     

  93.                     }  

  94.                     readCount = ftpStream.Read(buffer, 0, bufferSize);  

  95.                 }  

  96.                 ftpStream.Close();  

  97.                 outputStream.Close();  

  98.                 response.Close();  

  99.                 return true;  

  100.             }  

  101.             catch (Exception)  

  102.             {  

  103.                 return false;  

  104.                 throw;  

  105.             }  

  106.             finally  

  107.             {  

  108.                 if (ftpStream != null)  

  109.                 {  

  110.                     ftpStream.Close();  

  111.                 }  

  112.                 if (outputStream != null)  

  113.                 {  

  114.                     outputStream.Close();  

  115.                 }  

  116.                 if (response != null)  

  117.                 {  

  118.                     response.Close();  

  119.                 }  

  120.             }  

  121.         }  

  122.         /// <summary>  

  123.         /// 从FTP服务器下载文件,指定本地路径和本地文件名(支持断点下载)  

  124.         /// </summary>  

  125.         /// <param name="remoteFileName">远程文件名</param>  

  126.         /// <param name="localFileName">保存本地的文件名(包含路径)</param>  

  127.         /// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>  

  128.         /// <param name="size">已下载文件流大小</param>  

  129.         /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>  

  130.         /// <returns>是否下载成功</returns>  

  131.         public static bool FtpBrokenDownload(string remoteFileName, string localFileName, bool ifCredential, long size, Action<int, int> updateProgress = null)  

  132.         {  

  133.             FtpWebRequest reqFTP, ftpsize;  

  134.             Stream ftpStream = null;  

  135.             FtpWebResponse response = null;  

  136.             FileStream outputStream = null;  

  137.             try  

  138.             {  

  139.   

  140.                 outputStream = new FileStream(localFileName, FileMode.Append);  

  141.                 if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)  

  142.                 {  

  143.                     throw new Exception("ftp下载目标服务器地址未设置!");  

  144.                 }  

  145.                 Uri uri = new Uri("ftp://" + FtpServerIP + "/" + remoteFileName);  

  146.                 ftpsize = (FtpWebRequest)FtpWebRequest.Create(uri);  

  147.                 ftpsize.UseBinary = true;  

  148.                 ftpsize.ContentOffset = size;  

  149.   

  150.                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);  

  151.                 reqFTP.UseBinary = true;  

  152.                 reqFTP.KeepAlive = false;  

  153.                 reqFTP.ContentOffset = size;  

  154.                 if (ifCredential)//使用用户身份认证  

  155.                 {  

  156.                     ftpsize.Credentials = new NetworkCredential(FtpUserID, FtpPassword);  

  157.                     reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);  

  158.                 }  

  159.                 ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;  

  160.                 FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse();  

  161.                 long totalBytes = re.ContentLength;  

  162.                 re.Close();  

  163.   

  164.                 reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;  

  165.                 response = (FtpWebResponse)reqFTP.GetResponse();  

  166.                 ftpStream = response.GetResponseStream();  

  167.   

  168.                 //更新进度    

  169.                 if (updateProgress != null)  

  170.                 {  

  171.                     updateProgress((int)totalBytes, 0);//更新进度条     

  172.                 }  

  173.                 long totalDownloadedByte = 0;  

  174.                 int bufferSize = 2048;  

  175.                 int readCount;  

  176.                 byte[] buffer = new byte[bufferSize];  

  177.                 readCount = ftpStream.Read(buffer, 0, bufferSize);  

  178.                 while (readCount > 0)  

  179.                 {  

  180.                     totalDownloadedByte = readCount + totalDownloadedByte;  

  181.                     outputStream.Write(buffer, 0, readCount);  

  182.                     //更新进度    

  183.                     if (updateProgress != null)  

  184.                     {  

  185.                         updateProgress((int)totalBytes, (int)totalDownloadedByte);//更新进度条     

  186.                     }  

  187.                     readCount = ftpStream.Read(buffer, 0, bufferSize);  

  188.                 }  

  189.                 ftpStream.Close();  

  190.                 outputStream.Close();  

  191.                 response.Close();  

  192.                 return true;  

  193.             }  

  194.             catch (Exception)  

  195.             {  

  196.                 return false;  

  197.                 throw;  

  198.             }  

  199.             finally  

  200.             {  

  201.                 if (ftpStream != null)  

  202.                 {  

  203.                     ftpStream.Close();  

  204.                 }  

  205.                 if (outputStream != null)  

  206.                 {  

  207.                     outputStream.Close();  

  208.                 }  

  209.                 if (response != null)  

  210.                 {  

  211.                     response.Close();  

  212.                 }  

  213.             }  

  214.         }  

  215.   

  216.         /// <summary>  

  217.         /// 从FTP服务器下载文件,指定本地路径和本地文件名  

  218.         /// </summary>  

  219.         /// <param name="remoteFileName">远程文件名</param>  

  220.         /// <param name="localFileName">保存本地的文件名(包含路径)</param>  

  221.         /// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>  

  222.         /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>  

  223.         /// <param name="brokenOpen">是否断点下载:true 会在localFileName 找是否存在已经下载的文件,并计算文件流大小</param>  

  224.         /// <returns>是否下载成功</returns>  

  225.         public static bool FtpDownload(string remoteFileName, string localFileName, bool ifCredential, bool brokenOpen, Action<int, int> updateProgress = null)  

  226.         {  

  227.             if (brokenOpen)  

  228.             {  

  229.                 try  

  230.                 {  

  231.                     long size = 0;  

  232.                     if (File.Exists(localFileName))  

  233.                     {  

  234.                         using (FileStream outputStream = new FileStream(localFileName, FileMode.Open))  

  235.                         {  

  236.                             size = outputStream.Length;  

  237.                         }  

  238.                     }  

  239.                     return FtpBrokenDownload(remoteFileName, localFileName, ifCredential, size, updateProgress);  

  240.                 }  

  241.                 catch  

  242.                 {  

  243.                     throw;  

  244.                 }  

  245.             }  

  246.             else  

  247.             {  

  248.                 return FtpDownload(remoteFileName, localFileName, ifCredential, updateProgress);  

  249.             }  

  250.         }  

  251.         #endregion  

  252.  

  253.         #region 上传文件到FTP服务器  

  254.         /// <summary>  

  255.         /// 上传文件到FTP服务器  

  256.         /// </summary>  

  257.         /// <param name="localFullPath">本地带有完整路径的文件名</param>  

  258.         /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>  

  259.         /// <returns>是否下载成功</returns>  

  260.         public static bool FtpUploadFile(string localFullPathName, Action<int, int> updateProgress = null)  

  261.         {  

  262.             FtpWebRequest reqFTP;  

  263.             Stream stream = null;  

  264.             FtpWebResponse response = null;  

  265.             FileStream fs = null;  

  266.             try  

  267.             {  

  268.                 FileInfo finfo = new FileInfo(localFullPathName);  

  269.                 if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)  

  270.                 {  

  271.                     throw new Exception("ftp上传目标服务器地址未设置!");  

  272.                 }  

  273.                 Uri uri = new Uri("ftp://" + FtpServerIP + "/" + finfo.Name);  

  274.                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);  

  275.                 reqFTP.KeepAlive = false;  

  276.                 reqFTP.UseBinary = true;  

  277.                 reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);//用户,密码  

  278.                 reqFTP.Method = WebRequestMethods.Ftp.UploadFile;//向服务器发出下载请求命令  

  279.                 reqFTP.ContentLength = finfo.Length;//为request指定上传文件的大小  

  280.                 response = reqFTP.GetResponse() as FtpWebResponse;  

  281.                 reqFTP.ContentLength = finfo.Length;  

  282.                 int buffLength = 1024;  

  283.                 byte[] buff = new byte[buffLength];  

  284.                 int contentLen;  

  285.                 fs = finfo.OpenRead();  

  286.                 stream = reqFTP.GetRequestStream();  

  287.                 contentLen = fs.Read(buff, 0, buffLength);  

  288.                 int allbye = (int)finfo.Length;  

  289.                 //更新进度    

  290.                 if (updateProgress != null)  

  291.                 {  

  292.                     updateProgress((int)allbye, 0);//更新进度条     

  293.                 }  

  294.                 int startbye = 0;  

  295.                 while (contentLen != 0)  

  296.                 {  

  297.                     startbye = contentLen + startbye;  

  298.                     stream.Write(buff, 0, contentLen);  

  299.                     //更新进度    

  300.                     if (updateProgress != null)  

  301.                     {  

  302.                         updateProgress((int)allbye, (int)startbye);//更新进度条     

  303.                     }  

  304.                     contentLen = fs.Read(buff, 0, buffLength);  

  305.                 }  

  306.                 stream.Close();  

  307.                 fs.Close();  

  308.                 response.Close();  

  309.                 return true;  

  310.   

  311.             }  

  312.             catch (Exception)  

  313.             {  

  314.                 return false;  

  315.                 throw;  

  316.             }  

  317.             finally  

  318.             {  

  319.                 if (fs != null)  

  320.                 {  

  321.                     fs.Close();  

  322.                 }  

  323.                 if (stream != null)  

  324.                 {  

  325.                     stream.Close();  

  326.                 }  

  327.                 if (response != null)  

  328.                 {  

  329.                     response.Close();  

  330.                 }  

  331.             }  

  332.         }  

  333.   

  334.         /// <summary>  

  335.         /// 上传文件到FTP服务器(断点续传)  

  336.         /// </summary>  

  337.         /// <param name="localFullPath">本地文件全路径名称:C:\Users\JianKunKing\Desktop\IronPython脚本测试工具</param>  

  338.         /// <param name="remoteFilepath">远程文件所在文件夹路径</param>  

  339.         /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>  

  340.         /// <returns></returns>         

  341.         public static bool FtpUploadBroken(string localFullPath, string remoteFilepath, Action<int, int> updateProgress = null)  

  342.         {  

  343.             if (remoteFilepath == null)  

  344.             {  

  345.                 remoteFilepath = "";  

  346.             }  

  347.             string newFileName = string.Empty;  

  348.             bool success = true;  

  349.             FileInfo fileInf = new FileInfo(localFullPath);  

  350.             long allbye = (long)fileInf.Length;  

  351.             if (fileInf.Name.IndexOf("#") == -1)  

  352.             {  

  353.                 newFileName = RemoveSpaces(fileInf.Name);  

  354.             }  

  355.             else  

  356.             {  

  357.                 newFileName = fileInf.Name.Replace("#", "#");  

  358.                 newFileName = RemoveSpaces(newFileName);  

  359.             }  

  360.             long startfilesize = GetFileSize(newFileName, remoteFilepath);  

  361.             if (startfilesize >= allbye)  

  362.             {  

  363.                 return false;  

  364.             }  

  365.             long startbye = startfilesize;  

  366.             //更新进度    

  367.             if (updateProgress != null)  

  368.             {  

  369.                 updateProgress((int)allbye, (int)startfilesize);//更新进度条     

  370.             }  

  371.   

  372.             string uri;  

  373.             if (remoteFilepath.Length == 0)  

  374.             {  

  375.                 uri = "ftp://" + FtpServerIP + "/" + newFileName;  

  376.             }  

  377.             else  

  378.             {  

  379.                 uri = "ftp://" + FtpServerIP + "/" + remoteFilepath + "/" + newFileName;  

  380.             }  

  381.             FtpWebRequest reqFTP;  

  382.             // 根据uri创建FtpWebRequest对象   

  383.             reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));  

  384.             // ftp用户名和密码   

  385.             reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);  

  386.             // 默认为true,连接不会被关闭   

  387.             // 在一个命令之后被执行   

  388.             reqFTP.KeepAlive = false;  

  389.             // 指定执行什么命令   

  390.             reqFTP.Method = WebRequestMethods.Ftp.AppendFile;  

  391.             // 指定数据传输类型   

  392.             reqFTP.UseBinary = true;  

  393.             // 上传文件时通知服务器文件的大小   

  394.             reqFTP.ContentLength = fileInf.Length;  

  395.             int buffLength = 2048;// 缓冲大小设置为2kb   

  396.             byte[] buff = new byte[buffLength];  

  397.             // 打开一个文件流 (System.IO.FileStream) 去读上传的文件   

  398.             FileStream fs = fileInf.OpenRead();  

  399.             Stream strm = null;  

  400.             try  

  401.             {  

  402.                 // 把上传的文件写入流   

  403.                 strm = reqFTP.GetRequestStream();  

  404.                 // 每次读文件流的2kb     

  405.                 fs.Seek(startfilesize, 0);  

  406.                 int contentLen = fs.Read(buff, 0, buffLength);  

  407.                 // 流内容没有结束   

  408.                 while (contentLen != 0)  

  409.                 {  

  410.                     // 把内容从file stream 写入 upload stream   

  411.                     strm.Write(buff, 0, contentLen);  

  412.                     contentLen = fs.Read(buff, 0, buffLength);  

  413.                     startbye += contentLen;  

  414.                     //更新进度    

  415.                     if (updateProgress != null)  

  416.                     {  

  417.                         updateProgress((int)allbye, (int)startbye);//更新进度条     

  418.                     }  

  419.                 }  

  420.                 // 关闭两个流   

  421.                 strm.Close();  

  422.                 fs.Close();  

  423.             }  

  424.             catch  

  425.             {  

  426.                 success = false;  

  427.                 throw;  

  428.             }  

  429.             finally  

  430.             {  

  431.                 if (fs != null)  

  432.                 {  

  433.                     fs.Close();  

  434.                 }  

  435.                 if (strm != null)  

  436.                 {  

  437.                     strm.Close();  

  438.                 }  

  439.             }  

  440.             return success;  

  441.         }  

  442.   

  443.         /// <summary>  

  444.         /// 去除空格  

  445.         /// </summary>  

  446.         /// <param name="str"></param>  

  447.         /// <returns></returns>  

  448.         private static string RemoveSpaces(string str)  

  449.         {  

  450.             string a = "";  

  451.             CharEnumerator CEnumerator = str.GetEnumerator();  

  452.             while (CEnumerator.MoveNext())  

  453.             {  

  454.                 byte[] array = new byte[1];  

  455.                 array = System.Text.Encoding.ASCII.GetBytes(CEnumerator.Current.ToString());  

  456.                 int asciicode = (short)(array[0]);  

  457.                 if (asciicode != 32)  

  458.                 {  

  459.                     a += CEnumerator.Current.ToString();  

  460.                 }  

  461.             }  

  462.             string sdate = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Hour.ToString()  

  463.                 + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString();  

  464.             return a.Split('.')[a.Split('.').Length - 2] + "." + a.Split('.')[a.Split('.').Length - 1];  

  465.         }  

  466.         /// <summary>  

  467.         /// 获取已上传文件大小  

  468.         /// </summary>  

  469.         /// <param name="filename">文件名称</param>  

  470.         /// <param name="path">服务器文件路径</param>  

  471.         /// <returns></returns>  

  472.         public static long GetFileSize(string filename, string remoteFilepath)  

  473.         {  

  474.             long filesize = 0;  

  475.             try  

  476.             {  

  477.                 FtpWebRequest reqFTP;  

  478.                 FileInfo fi = new FileInfo(filename);  

  479.                 string uri;  

  480.                 if (remoteFilepath.Length == 0)  

  481.                 {  

  482.                     uri = "ftp://" + FtpServerIP + "/" + fi.Name;  

  483.                 }  

  484.                 else  

  485.                 {  

  486.                     uri = "ftp://" + FtpServerIP + "/" + remoteFilepath + "/" + fi.Name;  

  487.                 }  

  488.                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);  

  489.                 reqFTP.KeepAlive = false;  

  490.                 reqFTP.UseBinary = true;  

  491.                 reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);//用户,密码  

  492.                 reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;  

  493.                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();  

  494.                 filesize = response.ContentLength;  

  495.                 return filesize;  

  496.             }  

  497.             catch  

  498.             {  

  499.                 return 0;  

  500.             }  

  501.         }  

  502.   

  503.         //public void Connect(String path, string ftpUserID, string ftpPassword)//连接ftp  

  504.         //{  

  505.         //    // 根据uri创建FtpWebRequest对象  

  506.         //    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));  

  507.         //    // 指定数据传输类型  

  508.         //    reqFTP.UseBinary = true;  

  509.         //    // ftp用户名和密码  

  510.         //    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);  

  511.         //}  

  512.  

  513.         #endregion  

  514.   

  515.   

  516.   

  517.     }  

  518. }


该文章在 2024/1/12 21:06:19 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2024 ClickSun All Rights Reserved