zoukankan      html  css  js  c++  java
  • ftp文件上传和下载

      1 using System;
      2 using System.Collections.Generic;
      3 using System.Linq;
      4 using System.Text;
      5 using System.Net;
      6 using System.Threading;
      7 using System.IO;
      8 
      9 namespace FtpHelper
     10 {
     11     public delegate void DownloadCompleteHandler();
     12     public delegate void DownloadProgressHandler(int bytesRead, int totalBytes);
     13     /// <summary>
     14     /// ftp下载类
     15     /// </summary>
     16     public class FtpDownload
     17     {
     18         public DownloadCompleteHandler CompleteCallback;
     19         public DownloadProgressHandler ProgressCallback;
     20         private FtpWebRequest reqFTP = null;
     21         private FtpWebResponse resFTP = null;
     22         private Thread mThread = null;
     23         //下载文件到本地的存储路径
     24         private string sFileName = string.Empty;
     25 
     26         public string DlFileName
     27         {
     28             get { return sFileName; }
     29             set { sFileName = value; }
     30         }
     31         private FileStream outputStream = null;
     32         private Stream ftpStream = null;
     33         public bool IsComplete = false;
     34         //用于终止下载
     35         private bool stopFlag = false;
     36         //从Ftp下载的文件路径,示例:"ftp://192.168.2.200/Project/asss.xls"
     37         private string sFtpUrl = string.Empty;
     38         private string sFtpUser = string.Empty;
     39         private string sFtpPassword = string.Empty;
     40         public int BytesProcessed;
     41 
     42         public FtpDownload(string sUrlPath, string ftpUser, string ftpPassword)
     43         {
     44             sFtpUrl = sUrlPath;
     45             sFtpUser = ftpUser;
     46             sFtpPassword = ftpPassword;
     47 
     48         }
     49         /// <summary>
     50         /// 后台下载
     51         /// </summary>
     52         public void DownloadBackgroundFile()
     53         {
     54             if (CompleteCallback == null)
     55                 throw new ArgumentException("No download complete callback specified.");
     56             //实例化下载线程
     57             mThread = new Thread(new ThreadStart(Download));
     58             mThread.Name = "WebDownload.dlThread";
     59             mThread.IsBackground = true;
     60             mThread.CurrentUICulture = Thread.CurrentThread.CurrentUICulture;
     61             //开启后台下载线程
     62             mThread.Start();
     63         }
     64         protected void Download()
     65         {
     66             try
     67             {
     68                 if (stopFlag)
     69                 {
     70                     IsComplete = true;
     71                     return;
     72                 }
     73                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(sFtpUrl));
     74                 reqFTP.UseBinary = true;
     75                 reqFTP.Proxy = null;
     76                 reqFTP.UsePassive = false;
     77                 reqFTP.Credentials = new NetworkCredential(sFtpUser, sFtpPassword);
     78                 if (stopFlag)
     79                 {
     80                     IsComplete = true;
     81                     return;
     82                 }
     83                 resFTP = (FtpWebResponse)reqFTP.GetResponse();
     84                 ftpStream = resFTP.GetResponseStream();
     85                 long ContentLength = resFTP.ContentLength;
     86                 int bufferSize = 2048;
     87                 byte[] readBuffer = new byte[bufferSize];
     88                 outputStream = new FileStream(sFileName, FileMode.Create);
     89                 while (true)
     90                 {
     91                     if (stopFlag)
     92                     {
     93                         IsComplete = true;
     94                         return;
     95                     }
     96                     //  Pass do.readBuffer to BeginRead.
     97                     int bytesRead = ftpStream.Read(readBuffer, 0, bufferSize);
     98                     if (bytesRead <= 0)
     99                         break;
    100                     outputStream.Write(readBuffer, 0, bytesRead);
    101                     BytesProcessed += bytesRead;
    102                     OnProgressCallback(BytesProcessed, (int)ContentLength);
    103                 }
    104 
    105                 OnCompleteCallback();
    106             }
    107             catch (Exception ex)
    108             {
    109                 try
    110                 {
    111                     // Remove broken file download
    112                     if (outputStream != null)
    113                     {
    114                         outputStream.Close();
    115                         outputStream = null;
    116                     }
    117                     if (sFileName != null && sFileName.Length > 0)
    118                     {
    119                         File.Delete(sFileName);
    120                     }
    121                 }
    122                 catch (Exception)
    123                 {
    124                 }
    125                 Logger.Log.Write(ex.Message);
    126             }
    127             finally
    128             {
    129                 if (resFTP != null)
    130                 {
    131                     resFTP.Close();
    132                     resFTP = null;
    133                 }
    134                 if (ftpStream != null)
    135                 {
    136                     ftpStream.Close();
    137                     ftpStream.Dispose();
    138                 }
    139                 if (outputStream != null)
    140                 {
    141                     outputStream.Close();
    142                     outputStream.Dispose();
    143                 }
    144                 IsComplete = true;
    145             }
    146 
    147         }
    148 
    149         private void OnProgressCallback(int bytesRead, int totalBytes)
    150         {
    151             if (ProgressCallback != null)
    152             {
    153                 ProgressCallback(bytesRead, totalBytes);
    154             }
    155         }
    156         private void OnCompleteCallback()
    157         {
    158             if (CompleteCallback != null)
    159             {
    160                 CompleteCallback();
    161             }
    162         }
    163         /// 终止当前下载
    164         /// </summary>
    165         public void Cancel()
    166         {
    167             CompleteCallback = null;
    168             ProgressCallback = null;
    169             if (mThread != null && mThread != Thread.CurrentThread)
    170             {
    171                 if (mThread.IsAlive)
    172                 {
    173                     // Log.Write(Log.Levels.Verbose, "WebDownload.Cancel() : stopping download thread...");
    174                     stopFlag = true;
    175                     if (!mThread.Join(500))
    176                     {
    177                         //Log.Write(Log.Levels.Warning, "WebDownload.Cancel() : download thread refuses to die, forcing Abort()");
    178                         mThread.Abort();
    179                     }
    180                 }
    181                 mThread = null;
    182             }
    183         }
    184 
    185         public void Dispose()
    186         {
    187             if (mThread != null && mThread != Thread.CurrentThread)
    188             {
    189                 if (mThread.IsAlive)
    190                 {
    191                     // Log.Write(Log.Levels.Verbose, "WebDownload.Dispose() : stopping download thread...");
    192                     stopFlag = true;
    193                     if (!mThread.Join(500))
    194                     {
    195                         // Log.Write(Log.Levels.Warning, "WebDownload.Dispose() : download thread refuses to die, forcing Abort()");
    196                         mThread.Abort();
    197                     }
    198                 }
    199                 mThread = null;
    200             }
    201 
    202             if (reqFTP != null)
    203             {
    204                 reqFTP.Abort();
    205                 reqFTP = null;
    206             }
    207 
    208             if (outputStream != null)
    209             {
    210                 outputStream.Close();
    211                 outputStream = null;
    212             }
    213 
    214             //if (DownloadStartTime != DateTime.MinValue)
    215             //    OnDebugCallback(this);
    216 
    217             GC.SuppressFinalize(this);
    218         }
    219     }
    220 }
    View Code
      1 using System;
      2 using System.Collections.Generic;
      3 using System.Linq;
      4 using System.Text;
      5 using System.Net;
      6 using System.Threading;
      7 using System.IO;
      8 
      9 namespace FtpHelper
     10 {
     11     public delegate void UploadCompleteHandler();
     12     public delegate void UploadProgressHandler(int bytesRead, int totalBytes);
     13     public class FtpUpload
     14     {
     15         public UploadCompleteHandler CompleteCallback;
     16         public UploadProgressHandler ProgressCallback;
     17         private FtpWebRequest reqFTP;
     18         private FtpWebResponse resFTP;
     19         private Thread mThread = null;
     20         //本地文件路径
     21         private string sFileName = string.Empty;
     22 
     23         public string UlFileName
     24         {
     25             get { return sFileName; }
     26             set { sFileName = value; }
     27         }
     28         private Stream uploadStream = null;
     29         public bool IsComplete = false;
     30         //用于终止上传
     31         private bool stopFlag = false;
     32         //上传到Ftp路径,示例:"ftp://192.168.2.200/Project/asss.xls"
     33         private string sFtpUrl = string.Empty;
     34         private string sFtpUser = string.Empty;
     35         private string sFtpPassword = string.Empty;
     36         private int BytesProcessed;
     37         public FtpUpload(string sUrlPath, string ftpUser, string ftpPassword)
     38         {
     39             sFtpUrl = sUrlPath;
     40             sFtpUser = ftpUser;
     41             sFtpPassword = ftpPassword;
     42         }
     43 
     44         /// <summary>
     45         /// 后台上传
     46         /// </summary>
     47         public void UploadBackgroundFile()
     48         {
     49             if (CompleteCallback == null)
     50                 throw new ArgumentException("未定义上传成功后执行的回调函数!");
     51             //实例化下载线程
     52             mThread = new Thread(new ThreadStart(Upload));
     53             mThread.Name = "upload";
     54             mThread.IsBackground = true;
     55             mThread.CurrentUICulture = Thread.CurrentThread.CurrentUICulture;
     56             //开启后台下载线程
     57             mThread.Start();
     58         }
     59         protected void Upload()
     60         {
     61             using (FileStream fileStream = new FileStream(sFileName, FileMode.Open))
     62             {
     63                 byte[] fsdata = new byte[Convert.ToInt32(fileStream.Length)];
     64                 fileStream.Read(fsdata, 0, Convert.ToInt32(fileStream.Length));
     65                 try
     66                 {
     67                     if (stopFlag)
     68                     {
     69                         IsComplete = true;
     70                         return;
     71                     }
     72                     reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(sFtpUrl));
     73                     reqFTP.UseBinary = true;
     74                     reqFTP.Proxy = null;
     75                     reqFTP.UsePassive = false;
     76                     reqFTP.Credentials = new NetworkCredential(sFtpUser, sFtpPassword);
     77                     if (stopFlag)
     78                     {
     79                         IsComplete = true;
     80                         return;
     81                     }
     82 
     83                     reqFTP.KeepAlive = false;
     84                     reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
     85                     reqFTP.ContentLength = fileStream.Length;
     86 
     87                     int buffLength = 2048;
     88                     byte[] buffer = new byte[buffLength];
     89 
     90                     uploadStream = reqFTP.GetRequestStream();
     91                     fileStream.Position = 0;
     92                     while (true)
     93                     {
     94                         if (stopFlag)
     95                         {
     96                             IsComplete = true;
     97                             return;
     98                         }
     99                         int bytesRead = fileStream.Read(buffer, 0, buffLength);
    100                         if (bytesRead <= 0)
    101                             break;
    102                         uploadStream.Write(buffer, 0, bytesRead);
    103 
    104                         BytesProcessed += bytesRead;
    105                         OnProgressCallback(BytesProcessed, (int)reqFTP.ContentLength);
    106                     }               
    107                     OnCompleteCallback();
    108                 }
    109                 catch (Exception ex)
    110                 {
    111                     if (fileStream != null)
    112                     {
    113                         fileStream.Close();
    114                         //fileStream = null;
    115                     }
    116                     Logger.Log.Write(ex.Message);
    117                     //throw;
    118                 }
    119                 finally
    120                 {
    121                     if (uploadStream != null)
    122                     {
    123                         uploadStream.Close();
    124                         uploadStream.Dispose();
    125                     }
    126                     reqFTP = null;
    127                     IsComplete = true;
    128                 }
    129             }
    130         }
    131         private void OnProgressCallback(int bytesRead, int totalBytes)
    132         {
    133             if (ProgressCallback != null)
    134             {
    135                 ProgressCallback(bytesRead, totalBytes);
    136             }
    137         }
    138         private void OnCompleteCallback()
    139         {
    140             if (CompleteCallback != null)
    141             {
    142                 CompleteCallback();
    143             }
    144         }
    145         /// 终止当前下载
    146         /// </summary>
    147         public void Cancel()
    148         {
    149             CompleteCallback = null;
    150             ProgressCallback = null;
    151             if (mThread != null && mThread != Thread.CurrentThread)
    152             {
    153                 if (mThread.IsAlive)
    154                 {
    155                     // Log.Write(Log.Levels.Verbose, "WebDownload.Cancel() : stopping download thread...");
    156                     stopFlag = true;
    157                     if (!mThread.Join(500))
    158                     {
    159                         //Log.Write(Log.Levels.Warning, "WebDownload.Cancel() : download thread refuses to die, forcing Abort()");
    160                         mThread.Abort();
    161                     }
    162                 }
    163                 mThread = null;
    164             }
    165         }
    166 
    167         public void Dispose()
    168         {
    169             if (mThread != null && mThread != Thread.CurrentThread)
    170             {
    171                 if (mThread.IsAlive)
    172                 {
    173                     // Log.Write(Log.Levels.Verbose, "WebDownload.Dispose() : stopping download thread...");
    174                     stopFlag = true;
    175                     if (!mThread.Join(500))
    176                     {
    177                          //Log.Write(Log.Levels.Warning, "WebDownload.Dispose() : download thread refuses to die, forcing Abort()");
    178                         mThread.Abort();
    179                     }
    180                 }
    181                 mThread = null;
    182             }
    183 
    184             if (reqFTP != null)
    185             {
    186                 reqFTP.Abort();
    187                 reqFTP = null;
    188             }
    189 
    190             //if (DownloadStartTime != DateTime.MinValue)
    191             //    OnDebugCallback(this);
    192             GC.SuppressFinalize(this);
    193         }
    194 
    195     }
    196 }
    View Code
  • 相关阅读:
    为你的 Github 博客加个 CMS -「内容管理」
    Alpha、Beta、RC、GA、LTS等软件各个版本号的含义
    WPF圆形进度条
    初试WPF代码迁移Core WPF
    dumpbin查看(Exe,Dll)是32位还是64位
    Windows Live Writer使用SyntaxHighlighter代码着色插件
    C#调用EnumDevice获取设备信息
    C#获取设备(Audio和Video)名称 简单整理
    C# Winform 换肤
    C# Winform模仿百度日历
  • 原文地址:https://www.cnblogs.com/yhlx125/p/3337383.html
Copyright © 2011-2022 走看看