• C# FTP上传下载(支持断点续传)


     

    1. <pre class="csharp" name="code"><pre class="csharp" name="code">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:UsersJianKunKingDesktopIronPython脚本测试工具</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. }</pre><br></pre>  
    [csharp] view plain copy
     
    print?
    1. <pre class="csharp" name="code">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:UsersJianKunKingDesktopIronPython脚本测试工具</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. }</pre><br>  
    [csharp] view plain copy
     
    print?
    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:UsersJianKunKingDesktopIronPython脚本测试工具</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. }  
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;
    using System.IO;
    
    namespace JianKunKing.Common.Ftp
    {
        /// <summary>
        /// ftp方式文件下载上传
        /// </summary>
        public static class FileUpDownload
        {
            #region 变量属性
            /// <summary>
            /// Ftp服务器ip
            /// </summary>
            public static string FtpServerIP = string.Empty;
            /// <summary>
            /// Ftp 指定用户名
            /// </summary>
            public static string FtpUserID = string.Empty;
            /// <summary>
            /// Ftp 指定用户密码
            /// </summary>
            public static string FtpPassword = string.Empty;
    
            #endregion
    
            #region 从FTP服务器下载文件,指定本地路径和本地文件名
            /// <summary>
            /// 从FTP服务器下载文件,指定本地路径和本地文件名
            /// </summary>
            /// <param name="remoteFileName">远程文件名</param>
            /// <param name="localFileName">保存本地的文件名(包含路径)</param>
            /// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
            /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
            /// <returns>是否下载成功</returns>
            public static bool FtpDownload(string remoteFileName, string localFileName, bool ifCredential, Action<int, int> updateProgress = null)
            {
                FtpWebRequest reqFTP, ftpsize;
                Stream ftpStream = null;
                FtpWebResponse response = null;
                FileStream outputStream = null;
                try
                {
    
                    outputStream = new FileStream(localFileName, FileMode.Create);
                    if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)
                    {
                        throw new Exception("ftp下载目标服务器地址未设置!");
                    }
                    Uri uri = new Uri("ftp://" + FtpServerIP + "/" + remoteFileName);
                    ftpsize = (FtpWebRequest)FtpWebRequest.Create(uri);
                    ftpsize.UseBinary = true;
    
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
                    reqFTP.UseBinary = true;
                    reqFTP.KeepAlive = false;
                    if (ifCredential)//使用用户身份认证
                    {
                        ftpsize.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
                        reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
                    }
                    ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
                    FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse();
                    long totalBytes = re.ContentLength;
                    re.Close();
    
                    reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                    response = (FtpWebResponse)reqFTP.GetResponse();
                    ftpStream = response.GetResponseStream();
    
                    //更新进度  
                    if (updateProgress != null)
                    {
                        updateProgress((int)totalBytes, 0);//更新进度条   
                    }
                    long totalDownloadedByte = 0;
                    int bufferSize = 2048;
                    int readCount;
                    byte[] buffer = new byte[bufferSize];
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                    while (readCount > 0)
                    {
                        totalDownloadedByte = readCount + totalDownloadedByte;
                        outputStream.Write(buffer, 0, readCount);
                        //更新进度  
                        if (updateProgress != null)
                        {
                            updateProgress((int)totalBytes, (int)totalDownloadedByte);//更新进度条   
                        }
                        readCount = ftpStream.Read(buffer, 0, bufferSize);
                    }
                    ftpStream.Close();
                    outputStream.Close();
                    response.Close();
                    return true;
                }
                catch (Exception)
                {
                    return false;
                    throw;
                }
                finally
                {
                    if (ftpStream != null)
                    {
                        ftpStream.Close();
                    }
                    if (outputStream != null)
                    {
                        outputStream.Close();
                    }
                    if (response != null)
                    {
                        response.Close();
                    }
                }
            }
            /// <summary>
            /// 从FTP服务器下载文件,指定本地路径和本地文件名(支持断点下载)
            /// </summary>
            /// <param name="remoteFileName">远程文件名</param>
            /// <param name="localFileName">保存本地的文件名(包含路径)</param>
            /// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
            /// <param name="size">已下载文件流大小</param>
            /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
            /// <returns>是否下载成功</returns>
            public static bool FtpBrokenDownload(string remoteFileName, string localFileName, bool ifCredential, long size, Action<int, int> updateProgress = null)
            {
                FtpWebRequest reqFTP, ftpsize;
                Stream ftpStream = null;
                FtpWebResponse response = null;
                FileStream outputStream = null;
                try
                {
    
                    outputStream = new FileStream(localFileName, FileMode.Append);
                    if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)
                    {
                        throw new Exception("ftp下载目标服务器地址未设置!");
                    }
                    Uri uri = new Uri("ftp://" + FtpServerIP + "/" + remoteFileName);
                    ftpsize = (FtpWebRequest)FtpWebRequest.Create(uri);
                    ftpsize.UseBinary = true;
                    ftpsize.ContentOffset = size;
    
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
                    reqFTP.UseBinary = true;
                    reqFTP.KeepAlive = false;
                    reqFTP.ContentOffset = size;
                    if (ifCredential)//使用用户身份认证
                    {
                        ftpsize.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
                        reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
                    }
                    ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
                    FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse();
                    long totalBytes = re.ContentLength;
                    re.Close();
    
                    reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                    response = (FtpWebResponse)reqFTP.GetResponse();
                    ftpStream = response.GetResponseStream();
    
                    //更新进度  
                    if (updateProgress != null)
                    {
                        updateProgress((int)totalBytes, 0);//更新进度条   
                    }
                    long totalDownloadedByte = 0;
                    int bufferSize = 2048;
                    int readCount;
                    byte[] buffer = new byte[bufferSize];
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                    while (readCount > 0)
                    {
                        totalDownloadedByte = readCount + totalDownloadedByte;
                        outputStream.Write(buffer, 0, readCount);
                        //更新进度  
                        if (updateProgress != null)
                        {
                            updateProgress((int)totalBytes, (int)totalDownloadedByte);//更新进度条   
                        }
                        readCount = ftpStream.Read(buffer, 0, bufferSize);
                    }
                    ftpStream.Close();
                    outputStream.Close();
                    response.Close();
                    return true;
                }
                catch (Exception)
                {
                    return false;
                    throw;
                }
                finally
                {
                    if (ftpStream != null)
                    {
                        ftpStream.Close();
                    }
                    if (outputStream != null)
                    {
                        outputStream.Close();
                    }
                    if (response != null)
                    {
                        response.Close();
                    }
                }
            }
    
            /// <summary>
            /// 从FTP服务器下载文件,指定本地路径和本地文件名
            /// </summary>
            /// <param name="remoteFileName">远程文件名</param>
            /// <param name="localFileName">保存本地的文件名(包含路径)</param>
            /// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
            /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
            /// <param name="brokenOpen">是否断点下载:true 会在localFileName 找是否存在已经下载的文件,并计算文件流大小</param>
            /// <returns>是否下载成功</returns>
            public static bool FtpDownload(string remoteFileName, string localFileName, bool ifCredential, bool brokenOpen, Action<int, int> updateProgress = null)
            {
                if (brokenOpen)
                {
                    try
                    {
                        long size = 0;
                        if (File.Exists(localFileName))
                        {
                            using (FileStream outputStream = new FileStream(localFileName, FileMode.Open))
                            {
                                size = outputStream.Length;
                            }
                        }
                        return FtpBrokenDownload(remoteFileName, localFileName, ifCredential, size, updateProgress);
                    }
                    catch
                    {
                        throw;
                    }
                }
                else
                {
                    return FtpDownload(remoteFileName, localFileName, ifCredential, updateProgress);
                }
            }
            #endregion
    
            #region 上传文件到FTP服务器
            /// <summary>
            /// 上传文件到FTP服务器
            /// </summary>
            /// <param name="localFullPath">本地带有完整路径的文件名</param>
            /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
            /// <returns>是否下载成功</returns>
            public static bool FtpUploadFile(string localFullPathName, Action<int, int> updateProgress = null)
            {
                FtpWebRequest reqFTP;
                Stream stream = null;
                FtpWebResponse response = null;
                FileStream fs = null;
                try
                {
                    FileInfo finfo = new FileInfo(localFullPathName);
                    if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)
                    {
                        throw new Exception("ftp上传目标服务器地址未设置!");
                    }
                    Uri uri = new Uri("ftp://" + FtpServerIP + "/" + finfo.Name);
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
                    reqFTP.KeepAlive = false;
                    reqFTP.UseBinary = true;
                    reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);//用户,密码
                    reqFTP.Method = WebRequestMethods.Ftp.UploadFile;//向服务器发出下载请求命令
                    reqFTP.ContentLength = finfo.Length;//为request指定上传文件的大小
                    response = reqFTP.GetResponse() as FtpWebResponse;
                    reqFTP.ContentLength = finfo.Length;
                    int buffLength = 1024;
                    byte[] buff = new byte[buffLength];
                    int contentLen;
                    fs = finfo.OpenRead();
                    stream = reqFTP.GetRequestStream();
                    contentLen = fs.Read(buff, 0, buffLength);
                    int allbye = (int)finfo.Length;
                    //更新进度  
                    if (updateProgress != null)
                    {
                        updateProgress((int)allbye, 0);//更新进度条   
                    }
                    int startbye = 0;
                    while (contentLen != 0)
                    {
                        startbye = contentLen + startbye;
                        stream.Write(buff, 0, contentLen);
                        //更新进度  
                        if (updateProgress != null)
                        {
                            updateProgress((int)allbye, (int)startbye);//更新进度条   
                        }
                        contentLen = fs.Read(buff, 0, buffLength);
                    }
                    stream.Close();
                    fs.Close();
                    response.Close();
                    return true;
    
                }
                catch (Exception)
                {
                    return false;
                    throw;
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();
                    }
                    if (stream != null)
                    {
                        stream.Close();
                    }
                    if (response != null)
                    {
                        response.Close();
                    }
                }
            }
    
            /// <summary>
            /// 上传文件到FTP服务器(断点续传)
            /// </summary>
            /// <param name="localFullPath">本地文件全路径名称:C:UsersJianKunKingDesktopIronPython脚本测试工具</param>
            /// <param name="remoteFilepath">远程文件所在文件夹路径</param>
            /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
            /// <returns></returns>       
            public static bool FtpUploadBroken(string localFullPath, string remoteFilepath, Action<int, int> updateProgress = null)
            {
                if (remoteFilepath == null)
                {
                    remoteFilepath = "";
                }
                string newFileName = string.Empty;
                bool success = true;
                FileInfo fileInf = new FileInfo(localFullPath);
                long allbye = (long)fileInf.Length;
                if (fileInf.Name.IndexOf("#") == -1)
                {
                    newFileName = RemoveSpaces(fileInf.Name);
                }
                else
                {
                    newFileName = fileInf.Name.Replace("#", "#");
                    newFileName = RemoveSpaces(newFileName);
                }
                long startfilesize = GetFileSize(newFileName, remoteFilepath);
                if (startfilesize >= allbye)
                {
                    return false;
                }
                long startbye = startfilesize;
                //更新进度  
                if (updateProgress != null)
                {
                    updateProgress((int)allbye, (int)startfilesize);//更新进度条   
                }
    
                string uri;
                if (remoteFilepath.Length == 0)
                {
                    uri = "ftp://" + FtpServerIP + "/" + newFileName;
                }
                else
                {
                    uri = "ftp://" + FtpServerIP + "/" + remoteFilepath + "/" + newFileName;
                }
                FtpWebRequest reqFTP;
                // 根据uri创建FtpWebRequest对象 
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                // ftp用户名和密码 
                reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
                // 默认为true,连接不会被关闭 
                // 在一个命令之后被执行 
                reqFTP.KeepAlive = false;
                // 指定执行什么命令 
                reqFTP.Method = WebRequestMethods.Ftp.AppendFile;
                // 指定数据传输类型 
                reqFTP.UseBinary = true;
                // 上传文件时通知服务器文件的大小 
                reqFTP.ContentLength = fileInf.Length;
                int buffLength = 2048;// 缓冲大小设置为2kb 
                byte[] buff = new byte[buffLength];
                // 打开一个文件流 (System.IO.FileStream) 去读上传的文件 
                FileStream fs = fileInf.OpenRead();
                Stream strm = null;
                try
                {
                    // 把上传的文件写入流 
                    strm = reqFTP.GetRequestStream();
                    // 每次读文件流的2kb   
                    fs.Seek(startfilesize, 0);
                    int contentLen = fs.Read(buff, 0, buffLength);
                    // 流内容没有结束 
                    while (contentLen != 0)
                    {
                        // 把内容从file stream 写入 upload stream 
                        strm.Write(buff, 0, contentLen);
                        contentLen = fs.Read(buff, 0, buffLength);
                        startbye += contentLen;
                        //更新进度  
                        if (updateProgress != null)
                        {
                            updateProgress((int)allbye, (int)startbye);//更新进度条   
                        }
                    }
                    // 关闭两个流 
                    strm.Close();
                    fs.Close();
                }
                catch
                {
                    success = false;
                    throw;
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();
                    }
                    if (strm != null)
                    {
                        strm.Close();
                    }
                }
                return success;
            }
    
            /// <summary>
            /// 去除空格
            /// </summary>
            /// <param name="str"></param>
            /// <returns></returns>
            private static string RemoveSpaces(string str)
            {
                string a = "";
                CharEnumerator CEnumerator = str.GetEnumerator();
                while (CEnumerator.MoveNext())
                {
                    byte[] array = new byte[1];
                    array = System.Text.Encoding.ASCII.GetBytes(CEnumerator.Current.ToString());
                    int asciicode = (short)(array[0]);
                    if (asciicode != 32)
                    {
                        a += CEnumerator.Current.ToString();
                    }
                }
                string sdate = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Hour.ToString()
                    + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString();
                return a.Split('.')[a.Split('.').Length - 2] + "." + a.Split('.')[a.Split('.').Length - 1];
            }
            /// <summary>
            /// 获取已上传文件大小
            /// </summary>
            /// <param name="filename">文件名称</param>
            /// <param name="path">服务器文件路径</param>
            /// <returns></returns>
            public static long GetFileSize(string filename, string remoteFilepath)
            {
                long filesize = 0;
                try
                {
                    FtpWebRequest reqFTP;
                    FileInfo fi = new FileInfo(filename);
                    string uri;
                    if (remoteFilepath.Length == 0)
                    {
                        uri = "ftp://" + FtpServerIP + "/" + fi.Name;
                    }
                    else
                    {
                        uri = "ftp://" + FtpServerIP + "/" + remoteFilepath + "/" + fi.Name;
                    }
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
                    reqFTP.KeepAlive = false;
                    reqFTP.UseBinary = true;
                    reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);//用户,密码
                    reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                    filesize = response.ContentLength;
                    return filesize;
                }
                catch
                {
                    return 0;
                }
            }
    
            //public void Connect(String path, string ftpUserID, string ftpPassword)//连接ftp
            //{
            //    // 根据uri创建FtpWebRequest对象
            //    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
            //    // 指定数据传输类型
            //    reqFTP.UseBinary = true;
            //    // ftp用户名和密码
            //    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            //}
    
            #endregion
    
    
    
        }
    }

    调用实例:

    下载(不需要带iis部分的路径):

    [csharp] view plain copy
     
    print?
    1. FileUpDownload.FtpServerIP = "192.168.1.1";  
    2.            FileUpDownload.FtpUserID = "ftpTest001";  
    3.            FileUpDownload.FtpPassword = "aaaaaa";  
    4.            FileUpDownload.FtpDownload("Beyond Compare(绿色免安装).zip",  
    5.                Application.StartupPath + "/downloads/crm2.ra6", false);  
     FileUpDownload.FtpServerIP = "192.168.1.1";
                FileUpDownload.FtpUserID = "ftpTest001";
                FileUpDownload.FtpPassword = "aaaaaa";
                FileUpDownload.FtpDownload("Beyond Compare(绿色免安装).zip",
                    Application.StartupPath + "/downloads/crm2.ra6", false);

    之前的上传的文件目录:

    上传(不需要带iis部分的路径):
    [csharp] view plain copy
     
    print?
    1. OpenFileDialog op = new OpenFileDialog();  
    2.             op.InitialDirectory = Application.StartupPath;  
    3.             op.RestoreDirectory = true;  
    4.             op.Filter = "压缩文件(*.zip)|*.zip|压缩文件(*.rar)|*.rar|所有文件(*.*)|*.*";  
    5.             if (op.ShowDialog() == DialogResult.OK)  
    6.             {                 
    7.                 string aa = op.FileName;                 
    8.                 FileUpDownload.FtpServerIP = "192.168.1.1";  
    9.                 FileUpDownload.FtpUserID = "ftpTest001";  
    10.                 FileUpDownload.FtpPassword = "aaaaaa";  
    11.                 //全路径  
    12.                 FileUpDownload.FtpUploadFile(aa);                
    13.             }  
    OpenFileDialog op = new OpenFileDialog();
                op.InitialDirectory = Application.StartupPath;
                op.RestoreDirectory = true;
                op.Filter = "压缩文件(*.zip)|*.zip|压缩文件(*.rar)|*.rar|所有文件(*.*)|*.*";
                if (op.ShowDialog() == DialogResult.OK)
                {               
                    string aa = op.FileName;               
                    FileUpDownload.FtpServerIP = "192.168.1.1";
                    FileUpDownload.FtpUserID = "ftpTest001";
                    FileUpDownload.FtpPassword = "aaaaaa";
                    //全路径
                    FileUpDownload.FtpUploadFile(aa);              
                }

    IIS下搭建FTP服务器点击打开链接

    参考文章:点击打开链接
    小注:
    多线程下载:
    将文件分段,分段后,每段启用一个线程来下载(提供一个属性或者入参,来控制启用多少个线程),下载完成后,将文件拼起来(跟断点续传的原理差不多)
    具体可以百度搜索:c#  ftp  多线程 下载
  • 相关阅读:
    以太坊 生成助记词和infuru插件
    结束端口占用
    web3无法安装的额解决方案-----yarn命令安装web3
    npm无法安装全局web3的问题
    censeOs账户
    linux go环境安装
    一款非常好用的chrome插件Postman
    js页面刷新的方法location.reload()
    学会使用DNSPod,仅需三步
    wordpress博客服务器迁移过程中总结
  • 原文地址:https://www.cnblogs.com/lvdongjie/p/5570355.html
Copyright © 2020-2023  润新知