看到园子里有几篇关于c#连接ftp的文章,刚好最近刚刚完成对于这个的书写,就发出来给大家分享分享下。不会排版,第一次发,就直接贴代码了

View Code

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Text;
  4 using System.Configuration;
  5 using System.Net;
  6 using System.IO;
  7
  8 namespace MirroringDownClass
  9 {
 10     public class EasyononFtp
 11     {
 12         public  delegate void delegt(string s);
 13         public static event delegt onprogressBar;
 14         #region 成员
 15
 16
 17         private static string ftpServer ;  //ftp服务器地址
 18         private static string user;  //用户名
 19         private static string pwd;  //密码
 20         #endregion
 21
 22         FtpWebRequest reqFTP;
 23         FtpWebResponse ftpResponse;
 24         #region 构造函数
 25
 26         public EasyononFtp()
 27         {
 28         }
 29         public EasyononFtp(string ftpUri, string username, string password)
 30         {
 31             ftpServer = ftpUri;
 32             user = username;
 33             pwd = password;
 34         }
 35
 36         #endregion
 37         #region FTP连接
 38
 39         /// <summary>
 40         /// Ftp的连接
 41         /// </summary>
 42         /// <param name="url">ftp的地址</param>
 43         /// <returns>bool</returns>
 44         public  bool ftpconn()
 45         {
 46             try
 47             {
 48                 reqFTP = getFTPwbRequest(ftpServer, WebRequestMethods.Ftp.ListDirectoryDetails);
 49                 ftpResponse = (FtpWebResponse)reqFTP.GetResponse();
 50                 return true;
 51             }
 52             catch (Exception ex)
 53             {
 54                 Common.debugPrint(ex.Message.ToString());
 55             }
 56             finally
 57             {
 58                 if (ftpResponse != null)
 59                 {
 60                     ftpResponse.Close();
 61                 }
 62             }
 63             return false;
 64         }
 65         #endregion
 66         #region 下载FTP文件函数
 67        /// <summary>
 68         /// 下载
 69        /// </summary>
 70        /// <param name="desfilePath">本地文件目录</param>
 71        /// <param name="ftpfilePath">FTP服务器文件目录</param>
 72        /// <param name="fileName">带相对路径的文件名</param>
 73        /// <returns></returns>
 74         public bool ftpGetFile(string desfilePath, string ftpfilePath, string fileName)
 75         {
 76             string Relative_path = fileName.Replace("\\", "/");
 77             string filenamepath = ftpfilePath + "/" + Relative_path;
 78             try
 79             {
 80                 if (ftpconn())
 81                 {
 82                     Common.debugPrint(filenamepath + "下载中");
 83                     reqFTP = getFTPwbRequest(filenamepath, WebRequestMethods.Ftp.DownloadFile);
 84                     FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
 85                     Stream ftpStream = response.GetResponseStream();//FTP数据流
 86                     if (outputStream(desfilePath + "\\" + fileName, ftpStream))//字符流处理方法
 87                     {
 88                         ftpStream.Close();
 89                         response.Close();
 90                         Common.debugPrint(filenamepath + "下载完成!!!");
 91                         return true;
 92                     }
 93                     else
 94                         return false;
 95                 }
 96                 else
 97                 {
 98                     Common.debugPrint("ftpconn()连接失败");
 99                     return false;
100                 }
101             }
102             catch (Exception ex)
103             {
104                 Common.debugPrint(ex.Message.ToString() + "查看ftpGetFile函数");
105                 return false;
106             }
107         }
108         #endregion
109         #region 重写FTP下载函数
110       /// <summary>
111         /// 重写下载方法
112       /// </summary>
113       /// <param name="localFile">本地文件全路径</param>
114       /// <param name="ftpFile">ftp服务器文件全路径</param>
115       /// <returns></returns>
116         public bool ftpGetFile(string localFile, string ftpFile)
117         {
118             try
119             {
120                 if (ftpconn())
121                 {
122                     reqFTP = getFTPwbRequest(ftpFile, WebRequestMethods.Ftp.DownloadFile);
123                     FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
124                     Stream ftpStream = response.GetResponseStream();
125                     if (outputStream(localFile, ftpStream))//字符流处理方法
126                     {
127                         ftpStream.Close();
128                         response.Close();
129                         return true;
130                     }
131                     else
132                     {
133                         ftpStream.Close();
134                         response.Close();
135                         return false;
136                     }
137                 }
138                 else
139                 {
140                     Common.debugPrint("ftpconn()连接失败");
141                     return false;
142                 }
143
144             }
145             catch (Exception ex)
146             {
147                 Common.debugPrint(ex.Message.ToString());
148                 return false;
149             }
150         }
151        #endregion
152         #region 断点续传
153
154
155         /// <summary>
156         /// 断点续传(下载)
157         /// </summary>
158         /// <param name="localFile">本地文件路径</param>
159         /// <param name="ftpFile">FTP文件路径</param>
160         /// <returns>bool</returns>
161         public bool ftpGetBrokenFile(string localFile, string ftpFile)
162         {
163             try
164             {
165                 if (File.Exists(localFile))
166                 {
167                     FileInfo fileinfo = new FileInfo(localFile);
168                     long leng = fileinfo.Length;
169                     if (ftpconn())
170                     {
171                         if (leng < GetftpFilesLength(ftpFile) && leng < 1024 * 10000)
172                         {
173                             File.Delete(localFile);//删除重传
174                             Common.debugPrint(localFile + "删除重传");
175                             return ftpGetFile(localFile, ftpFile);//调用ftpGetFile
176                         }
177                         else// 断点续传
178                         {
179                             reqFTP = getFTPwbRequest(ftpFile, WebRequestMethods.Ftp.DownloadFile);
180                             reqFTP.ContentOffset = leng;
181                             FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
182                             Stream ftpStream = response.GetResponseStream();
183                             if (outputStream(localFile, ftpStream))//字符流处理方法
184                             {
185                                 ftpStream.Close();
186                                 response.Close();
187                                 Common.debugPrint(localFile + "断点续传完成");
188                                 return true;
189                             }
190                             else
191                             {
192                                 Common.debugPrint(localFile + "断点续传失败");
193                                 return false;
194                             }
195                         }
196                     }
197                     else
198                     {
199                         Common.debugPrint("ftpconn()连接失败");
200                         return false;
201                     }
202                 }
203                 else
204                 {
205                     return ftpGetFile(localFile, ftpFile);//调用ftpGetFile
206                 }
207             }
208             catch (Exception ex)
209             {
210                 Common.debugPrint(ex.Message.ToString()+"EasyonFtp类");
211                 return false;
212             }
213         }
214         #endregion
215         #region FTP上传
216         /// <summary>
217         ///  FTP上传方法
218         /// </summary>
219         /// <param name="localFile">本地文件全路径</param>
220         /// <param name="ftpFile">上传到ftp服务器的指定路径</param>
221         /// <param name="Breakpoint">断点处</param>
222         /// <returns></returns>
223         public bool ftpUpload(string localFile, string ftpFile, long Breakpoint)
224         {
225             if (Breakpoint > 0)
226             {
227                 reqFTP = getFTPwbRequest(ftpFile, WebRequestMethods.Ftp.AppendFile);
228             }
229             else
230             {
231                 reqFTP = getFTPwbRequest(ftpFile, WebRequestMethods.Ftp.UploadFile);
232             }
233             FileInfo fileinfo = new FileInfo(localFile);
234             Stream strm = reqFTP.GetRequestStream();
235             try
236             {
237                 // 上传文件时通知服务器文件的大小
238                 reqFTP.ContentLength = fileinfo.Length;
239                 //这里判断是否是断点续传
240
241                 if (inputStream(localFile, strm, Breakpoint))
242                 {
243                     return true;
244                 }
245                 else
246                 {
247                     Common.debugPrint("outputStream处理异常");
248                     return false;
249                 }
250             }
251             catch (Exception ex)
252             {
253                 Common.debugPrint(ex.Message);
254             }
255             finally
256             {
257                 strm.Close();
258             }
259             return false;
260         }
261
262         /// <summary>
263         /// 创建文件夹   (1J目录)
264         /// </summary>
265         /// <param name="ftpFile"></param>
266         public bool MaikDir(string ftpFile)
267         {
268             FtpWebResponse response = null;
269             try
270             {
271                 string uri = ftpFile;
272                 //Connect(uri);//连接
273                 reqFTP = getFTPwbRequest(ftpFile, WebRequestMethods.Ftp.MakeDirectory);
274                // reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
275                response = (FtpWebResponse)reqFTP.GetResponse();
276             }
277             catch (Exception ex)
278             {
279                 return false;
280                // MessageBox.Show(ex.Message);
281             }
282             finally
283             {
284                 if (response != null)
285                 {
286                     response.Close();
287                 }
288             }
289             return true;
290
291         }
292         #endregion
293         #region  获取ftp上文件最后修改时间
294
295         /// <summary>
296         /// 获取ftp上文件最后修改时间
297         /// </summary>
298         /// <param name="filename"></param>
299         /// <returns></returns>
300         public DateTime GetftpFileslastModifiedTime(string filename)
301         {
302             DateTime lastmodified = new DateTime();
303             try
304             {
305                 if (ftpconn())
306                 {
307                     reqFTP = getFTPwbRequest(filename, WebRequestMethods.Ftp.GetDateTimestamp);
308                     FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
309                     lastmodified = response.LastModified;
310                     response.Close();
311                 }
312             }
313             catch (Exception ex)
314             {
315                 Common.debugPrint(ex.Message + "EasyonFtp类 GetftpFileslastModifiedTime()");
316             }
317             return lastmodified;
318         }
319         #endregion
320         #region 获取FTP文件的长度
321
322
323         public long GetftpFilesLength(string filename)
324         {
325             long length = 0;
326             try
327             {
328                 if (ftpconn())
329                 {
330                     reqFTP = getFTPwbRequest(filename, WebRequestMethods.Ftp.GetFileSize);
331                     FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
332                     length = response.ContentLength;
333                 }
334             }
335             catch (Exception ex)
336             {
337                 Common.debugPrint(ex.Message + "EasyonFtp类 GetftpFilesLength() ");
338             }
339             return length;
340         }
341         #endregion
342         #region 获取ftp目录下文件信息
343
344         /// <summary>
345         /// 获取ftp目录下文件和文件夹信息(只获取当前目录信息)
346         /// </summary>
347         /// <param name="ftpFile">ftp目录</param>
348         /// <returns></returns>
349         public FileStruct[] ftpListFiles(string ftpFile)
350         {
351
352             FileStruct[] list = null;
353             try
354             {
355                 if (ftpconn())
356                 {
357                     reqFTP = getFTPwbRequest(ftpFile, WebRequestMethods.Ftp.ListDirectoryDetails);
358                     FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
359                     StreamReader stream = new StreamReader(response.GetResponseStream(), Encoding.Default);
360                     string Datastring = stream.ReadToEnd();
361                     DirectoryListParser parser = new DirectoryListParser(Datastring);
362                     list = parser.FullListing;
363                     response.Close();
364                     //char[] seperator = { '\n' };
365                     //list = Datastring.Split(seperator);
366
367                     return list;
368                 }
369             }
370             catch (Exception ex)
371             {
372                 Common.debugPrint(ex.Message + "EasyonFtp类 GetftpFilesLength()");
373             }
374             return list;
375         }
376         #endregion
377         #region FtpWebRequest请求
378
379         /// <summary>
380         /// 获取FtpWebRequest
381         /// </summary>
382         /// <param name="ftpFilepath">ftp文件/目录路径</param>
383         /// <param name="Method">WebRequestMethods.Ftp.Method</param>
384         /// <returns></returns>
385         public FtpWebRequest getFTPwbRequest(string ftpFilepath, string Method)
386         {
387             try
388             {
389                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpFilepath));
390                 reqFTP.Method = Method;
391                 reqFTP.KeepAlive = true;
392                 reqFTP.UseBinary = true;
393             }
394             catch (Exception ex)
395             {
396                 Common.debugPrint(ex.Message + "EasyononFtp获取FtpWebRequest失败");
397                 return null;
398             }
399             try
400             {
401                 reqFTP.Credentials = new NetworkCredential(user, pwd);
402
403             }
404             catch (Exception ex)
405             {
406                 Common.debugPrint(ex.Message);
407             }
408             return reqFTP;
409
410         }
411         public FtpWebRequest getFTPwbRequest1(string ftpFilepath, string Method)
412         {
413             try
414             {
415                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpFilepath));
416                 reqFTP.Method = Method;
417                 //reqFTP.KeepAlive = true;
418                 reqFTP.UseBinary = true;
419             }
420             catch (Exception ex)
421             {
422                 Common.debugPrint(ex.Message + "EasyononFtp获取FtpWebRequest失败");
423                 return null;
424             }
425             try
426             {
427                 reqFTP.Credentials = new NetworkCredential(user, pwd);
428
429             }
430             catch (Exception ex)
431             {
432                 Common.debugPrint(ex.Message);
433             }
434             return reqFTP;
435
436         }
437         #endregion
438         #region 下载文件流输出处理
439
440         /// <summary>
441         /// 下载文件流输出处理方法
442         /// </summary>
443         /// <param name="filePath">ftp文件路径</param>
444         /// <param name="ftpStream">IO流</param>
445         /// <returns></returns>
446         private bool outputStream(string filePath, Stream ftpStream)
447         {
448             FileStream outputStream  = new FileStream(filePath, FileMode.Append, FileAccess.Write);
449
450             int bufferSize = 2048*1000;
451
452             int readCount;
453
454             byte[] buffer = new byte[bufferSize];
455             try
456             {
457                 readCount = ftpStream.Read(buffer, 0, bufferSize);
458                 while (readCount > 0)
459                 {
460                     outputStream.Write(buffer, 0, readCount);
461                     readCount = ftpStream.Read(buffer, 0, bufferSize);
462                 }
463                 return true;
464             }
465             catch (Exception ex)
466             {
467                 Common.debugPrint(ex.Message.ToString() + "EasyononFtp类下载文件流输出处理方法异常");
468                 return false;
469             }
470             finally
471             {
472                 outputStream.Close();
473             }
474         }
475         #endregion
476         #region 上传文件流输出处理
477        /// <summary>
478         /// 上传文件流输出处理方法
479        /// </summary>
480        /// <param name="fileinfo">文件信息</param>
481        /// <param name="ftpStream">IO流</param>
482        /// <returns></returns>
483         private bool inputStream(string filePath, Stream ftpStream, long Breakpoint)
484         {
485
486             // 打开一个文件流(System.IO.FileStream) 去读上传的文件
487             FileStream outputStream = new FileStream(filePath, FileMode.Open);
488
489             // 缓冲大小设置为kb
490             int bufferSize = 2048 * 1000;
491
492             int readCount;
493
494             byte[] buffer = new byte[bufferSize];
495             try
496             {
497                 if (Breakpoint > 0)
498                 {
499                     outputStream.Seek(Breakpoint, SeekOrigin.Current);
500
501
502                 }
503
504                     readCount = outputStream.Read(buffer, 0, bufferSize);
505
506                 while (readCount > 0)
507                 {
508                     // 把内容从file stream 写入upload stream
509                     ftpStream.Write(buffer, 0, readCount);
510                     readCount = outputStream.Read(buffer, 0, bufferSize);
511
512                    //
513                 }
514
515                 return true;
516             }
517             catch (Exception ex)
518             {
519                 Common.debugPrint(ex.Message.ToString() + "上传文件流输出处理方法异常");
520                 return false;
521             }
522             finally
523             {
524                 outputStream.Close();
525             }
526         }
527         #endregion
528
529     }
530 }

如果有哪位大大能给排本提供帮助,在园子逛的也蛮久了,发现很多都排的挺漂亮的。

转载于:https://www.cnblogs.com/cnwisdom/archive/2012/12/28/2837112.html

关于ftp的功能类——下载,上传,断点,连接相关推荐

  1. 【代码审计-2】PHP框架MVC类文件上传断点测试挖掘

    1.文件上传漏洞挖掘: (1)关键字搜索(函数.键字.全局变量等):比如$_FILES,move_uploades_file等 (2)应该功能抓包:寻找任何可能存在上传的应用功能点,比如前台会员中心, ...

  2. VB FTP操作类(可上传、下载、创建文件夹等等)

    可实现FTP上传下载,建文件夹等功能,从网上找了一个类,对其进行修改和功能补充,正常使用,非常方便. 切记在使用FtpFindFirstFile 函数查找相应的文件或文件夹后,要使用InternetC ...

  3. 从FTP服务器进行文件的上传和下载

    .net 2.0(c#)下简单的FTP应用程序 本文使用.net 2.0(c#)来实现一般的FTP功能 介绍 微软的.net framework 2.0相对于1.x来说增加了对FTP的支持.以前为了符 ...

  4. FTP协议中的登录 上传 下载 新建目录 删除目录 的wireshark包分析(一文看完TCP包分析,附源文件,ppt,操作视频)

    ​​​​​​​目录 一原理 二.FTP登录 三.FTP下载 四.FTP上传 五.FTP新建目录 六.FTP删除目录 一原理 前言:TCP/IP四层模型和OSI模型对照,以及FTP在模型中的位置. • ...

  5. ftp 追加远程文件_ftp上传,完成ftp定时上传、下载只需3步

    FTP[File Transfer Protocol]中文译为文件传输协议,是Internet上的另一项主要服务,这项服务让使用者能通过Internet来传输各式各样的文件.FTP上传是与WEB上传相 ...

  6. FTP服务(文件的上传和下载)

    文章目录 一.FTP的作用 二.FTP的端口号 三.FTP:匿名.系统.虚拟账户 四.FTP匿名账户的部署 1.关闭防火墙 2.安装vsftp服务 3.编辑配置文件 4.修改属主和属组,并创建文件 5 ...

  7. ubuntu下搭建FTP服务器并使用FileZilla上传下载

    ubuntu下搭建FTP服务器并使用FileZilla上传下载 为了让实验室同学在共享文件时更加方便,我们决定在实验室电脑上搭建一个FTP服务器,ubuntu系统版本为16.04,下面就是我的搭建流程 ...

  8. 模拟部署FTP服务器并提供文件的上传及下载

    FTP(File Transfer Protocol:文件传输协议)是TCP/IP协议组中的协议之一,主要是提供文件共享服务. 数据端口20:用于传输数据: 控制端口21:用于传输指令: 操作环境:V ...

  9. 安卓项目实战之强大的网络请求框架okGo使用详解(一):实现get,post基本网络请求,下载上传进度监听以及对Callback自定义的深入理解

    1.添加依赖 //必须使用 compile 'com.lzy.net:okgo:3.0.4'//以下三个选择添加,okrx和okrx2不能同时使用,一般选择添加最新的rx2支持即可 compile ' ...

最新文章

  1. Gradle dependency cache may be corrupt
  2. android 增删改查 源码_学生信息增删改查小程序案例(springboot服务端)
  3. nyoj- 117 求逆序数 hdu-sort it---- 树状数组
  4. RabbitMQ消息追踪之Firehose
  5. 锁表的进程和语句,并杀掉
  6. 产品经理与项目经理的区别
  7. 华为云云容器快速搭建网站实践随记—利用公有镜像搭建WordPress
  8. 赛锐信息:SAP ABAP 常量和字面量
  9. 【HNOI 2016】大数
  10. SQL 复习二(数据查询语言)
  11. php url编码解码
  12. python 24点题目分析_24点游戏的递归解法和Python实现
  13. SoberGGG对针式PKM的初次测评
  14. spring boot 2.1.4 hibernate 二级缓存 Caffeine实现
  15. 中兴网络设备交换机路由器查看ARP表项命令方法
  16. BAT-批处理去除文件夹及子文件夹名子中的空格-并整理文件夹和子文件夹目录
  17. lv官网编码查询_成都市居住证编号查询系统
  18. 给UILabel中的文字加删除线
  19. 如何增强大脑记忆力?提高大脑记忆能力的20个方法
  20. 微信提示已连接到服务器失败,微信提示无法连接到服务器如何解决

热门文章

  1. 【CentOS】EOF使用
  2. 启用Windows Server 2012的远程桌面
  3. stripfxg php,代码审计| 适合练手的ZZCMS8.2漏洞
  4. docker 不挂断创建容器
  5. 预警数据一键升级工具_重磅 | 教务管理全新升级,“章鱼校长”助力机构实现轻松管理...
  6. python前后端分离前端权限_Linux上搭建前后端分离项目
  7. mysql stop很久_mysql的timeout
  8. 字符串匹配rk算法c语言,字符串匹配问题(BFRK算法)
  9. java 调用webapi json_java通过url调用web api并接收其返回的json
  10. tampermonkey怎么不能用了_发现键盘数字小键盘不能用怎么办?