FtpHelper.cs

网上找了好多,感觉还是自己这个使用起来方便点,记录一下!

  1 using System;
  2 using System.Collections;
  3 using System.IO;
  4 using System.Linq;
  5 using System.Net;
  6 using System.Text;
  7 
  8 namespace FtpTest.Common
  9 {
 10 
 11     public class FtpHelper
 12     {
 13         private readonly string _ftpUri;  //ftp服务器地址
 14         private readonly string _ftpName;  //ftp帐户
 15         private readonly string _ftpPwd;  //ftp密码
 16         private FtpWebRequest _ftpRequest;  //请求
 17         private FtpWebResponse _ftpResponse;  //响应
 18 
 19         public FtpHelper(string uri, string name, string password)
 20         {
 21             _ftpUri = uri;
 22             _ftpName = name;
 23             _ftpPwd = password;
 24         }
 25 
 26         /// <summary>
 27         /// 连接类
 28         /// </summary>
 29         /// <param name="uri">ftp地址</param>
 30         private void Conn(string uri)
 31         {
 32             _ftpRequest = (FtpWebRequest)WebRequest.Create(uri);
 33             //登录ftp服务器,ftpName:账户名,ftpPwd:密码
 34             _ftpRequest.Credentials = new NetworkCredential(_ftpName, _ftpPwd);
 35             _ftpRequest.UseBinary = true;  //该值指定文件传输的数据类型。
 36         }
 37 
 38         /// <summary>
 39         /// 删除文件
 40         /// </summary>
 41         /// <param name="fileName">文件名</param>
 42         public void DeleteFileName(string fileName)
 43         {
 44             string uri = _ftpUri + "/" + fileName;
 45             Conn(uri);
 46             try
 47             {
 48                 _ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
 49                 _ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse();
 50                 _ftpResponse.Close();
 51             }
 52             catch (Exception)
 53             {
 54                 // ignored
 55             }
 56         }
 57 
 58         /// <summary>
 59         /// 删除ftp上目录
 60         /// </summary>
 61         /// <param name="dirName"></param>
 62         public void RemoveDir(string dirName)
 63         {
 64             string uri = _ftpUri + "/" + dirName;
 65             Conn(uri);
 66             try
 67             {
 68                 _ftpRequest.Method = WebRequestMethods.Ftp.RemoveDirectory;
 69                 _ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse();
 70                 _ftpResponse.Close();
 71             }
 72             catch (Exception)
 73             {
 74                 // ignored
 75             }
 76         }
 77 
 78         /// <summary>
 79         /// 上传文件,使用FTPWebRequest、FTPWebResponse实例
 80         /// </summary>
 81         /// <param name="uri">ftp地址</param>
 82         /// <param name="fileName">文件名</param>
 83         /// <param name="fileData">文件内容</param>
 84         /// <param name="msg">传出参数,返回传输结果</param>
 85         public void UploadFile(string uri, string fileName, byte[] fileData, out string msg)
 86         {
 87             string ftpUri = uri.EndsWith("/") ? uri : uri + "/";
 88             ftpUri += fileName;
 89             //连接ftp服务器
 90             Conn(ftpUri);
 91             _ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
 92             _ftpRequest.ContentLength = fileData.Length; //上传文件时通知服务器文件的大小
 93             try
 94             {
 95                 //将文件流中的数据(byte[] fileData)写入请求流
 96                 using (Stream ftpstream = _ftpRequest.GetRequestStream())
 97                 {
 98                     ftpstream.Write(fileData, 0, fileData.Length);
 99                 }
100 
101                 _ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse(); //响应
102                 msg = _ftpResponse.StatusDescription; //响应状态
103                 _ftpResponse.Close();
104             }
105             catch (Exception exp)
106             {
107                 msg = "Failed to upload:" + exp.Message;
108             }
109         }
110 
111         /// <summary>
112         /// 上传文件,使用WebClient类
113         /// </summary>
114         /// <param name="uri">ftp地址</param>
115         /// <param name="fileName">文件名</param>
116         /// <param name="fileData">文件内容</param>
117         /// <param name="msg">传出参数,输出传输结果</param>
118         public void UploadFileByWebClient(string uri, string fileName, byte[] fileData, out string msg)
119         {
120             string ftpUri = uri.EndsWith("/") ? uri : uri + "/";
121             ftpUri += fileName;
122 
123             try
124             {
125                 WebClient client = new WebClient { Credentials = new NetworkCredential(_ftpName, _ftpPwd) };
126                 //登录FTP服务
127                 client.UploadData(ftpUri, "STOR", fileData); //指定为ftp上传方式
128                 msg = "上传成功!";
129             }
130             catch (Exception exp)
131             {
132                 msg = "Failed to upload:" + exp.Message;
133             }
134         }
135 
136         /// <summary>
137         /// 下载文件,使用FTPWebRequest、FTPWebResponse实例
138         /// </summary>
139         /// <param name="uri">ftp地址</param>
140         /// <param name="destinationDir">目标文件存放地址</param>
141         /// <param name="msg">传出参数,返回传输结果</param>
142         public void DownloadFile(string uri, string destinationDir, out string msg)
143         {
144             string fileName = Path.GetFileName(uri);
145             // ReSharper disable once AssignNullToNotNullAttribute
146             string destinationPath = Path.Combine(destinationDir, fileName);
147 
148             try
149             {
150                 //连接ftp服务器
151                 Conn(uri);
152 
153                 using (FileStream outputStream = new FileStream(destinationPath, FileMode.OpenOrCreate))
154                 {
155                     using (_ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse())
156                     {
157                         //将响应流中的数据写入到文件流
158                         using (Stream ftpStream = _ftpResponse.GetResponseStream())
159                         {
160                             int bufferSize = 2048;
161                             byte[] buffer = new byte[bufferSize];
162                             if (ftpStream != null)
163                             {
164                                 var readCount = ftpStream.Read(buffer, 0, bufferSize);
165                                 while (readCount > 0)
166                                 {
167                                     outputStream.Write(buffer, 0, readCount);
168                                     readCount = ftpStream.Read(buffer, 0, bufferSize);
169                                 }
170                             }
171                         }
172                         msg = _ftpResponse.StatusDescription;
173                     }
174                 }
175             }
176             catch (Exception exp)
177             {
178                 msg = "Failed to download:" + exp.Message;
179             }
180         }
181 
182         public byte[] DownloadFile()
183         {
184             try
185             {
186                 WebClient client = new WebClient { Credentials = new NetworkCredential(_ftpName, _ftpPwd) };
187                 byte[] responseData = client.DownloadData(_ftpUri);
188                 return responseData;
189             }
190             catch (Exception ex)
191             {
192                 // ReSharper disable once PossibleIntendedRethrow
193                 throw ex;
194             }
195         }
196 
197         /// <summary>
198         /// 文件下载,使用WebClient类
199         /// </summary>
200         /// <param name="uri">ftp服务地址</param>
201         /// <param name="destinationDir">存放目录</param>
202         public void DownloadFileByWebClient(string uri, string destinationDir)
203         {
204             string fileName = Path.GetFileName(uri);
205             // ReSharper disable once AssignNullToNotNullAttribute
206             string destinationPath = Path.Combine(destinationDir, fileName);
207 
208             try
209             {
210                 WebClient client = new WebClient { Credentials = new NetworkCredential(_ftpName, _ftpPwd) };
211 
212                 byte[] responseData = client.DownloadData(uri);
213 
214                 using (FileStream fileStream = new FileStream(destinationPath, FileMode.OpenOrCreate))
215                 {
216                     fileStream.Write(responseData, 0, responseData.Length);
217                 }
218             }
219             catch (Exception)
220             {
221                 // ignored
222             }
223         }
224 
225         /// <summary>
226         /// 遍历文件
227         /// </summary>
228         public ArrayList GetListDirectoryDetails()
229         {
230             ArrayList fileInfo = new ArrayList();
231             try
232             {
233                 Conn(_ftpUri);
234 
235                 //获取 FTP 服务器上的文件的详细列表的 FTP LIST 协议方法
236                 _ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
237                 try
238                 {
239                     _ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse(); //响应
240                 }
241                 catch (WebException)
242                 {
243                 }
244                 catch (InvalidOperationException)
245                 {
246                 }
247 
248                 using (Stream responseStream = _ftpResponse.GetResponseStream())
249                 {
250                     // ReSharper disable once AssignNullToNotNullAttribute
251                     using (StreamReader reader = new StreamReader(responseStream))
252                     {
253                         string line = reader.ReadLine();
254                         while (line != null)
255                         {
256                             fileInfo.Add(line);
257                             line = reader.ReadLine();
258                         }
259                     }
260                 }
261             }
262             catch (Exception)
263             {
264                 // ignored
265             }
266 
267             return fileInfo;
268         }
269 
270         /// <summary>
271         /// 上传图片
272         /// </summary>
273         /// <param name="mstr"></param>
274         /// <param name="ftpUri"></param>
275         /// <returns></returns>
276         public bool Upload(MemoryStream mstr, string ftpUri)
277         {
278             try
279             {
280                 FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(ftpUri);
281                 ftp.Credentials = new NetworkCredential(_ftpName, _ftpPwd);
282                 ftp.Method = WebRequestMethods.Ftp.UploadFile;
283                 ftp.UseBinary = true;
284                 ftp.UsePassive = true;
285                 using (Stream stream = ftp.GetRequestStream())
286                 {
287                     byte[] bytes = mstr.ToArray();
288                     stream.Write(bytes, 0, bytes.Length);
289                     stream.Close();
290                     mstr.Close();
291                 }
292                 return true;
293             }
294             catch (Exception)
295             {
296                 return false;
297             }
298         }
299 
300         public bool Upload(byte[] mstr, string ftpUri)
301         {
302             try
303             {
304                 FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(ftpUri);
305                 ftp.Credentials = new NetworkCredential(_ftpName, _ftpPwd);
306                 ftp.Method = WebRequestMethods.Ftp.UploadFile;
307                 ftp.UseBinary = true;
308                 ftp.UsePassive = true;
309                 using (Stream stream = ftp.GetRequestStream())
310                 {
311                     stream.Write(mstr, 0, mstr.Length);
312                     stream.Close();
313                 }
314                 return true;
315             }
316             catch (Exception)
317             {
318                 return false;
319             }
320         }
321 
322         /// <summary>
323         /// 重命名文件
324         /// </summary>
325         /// <param name="fileName">原文件名</param>
326         /// <param name="reNameFileName">新文件名</param>
327         public bool RenameFileName(string fileName, string reNameFileName)
328         {
329             bool result = true;
330             FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(reNameFileName);
331             ftp.Credentials = new NetworkCredential(_ftpName, _ftpPwd);
332             try
333             {
334                 ftp.Method = WebRequestMethods.Ftp.Rename;
335                 ftp.RenameTo = fileName;
336                 ftp.UseBinary = true;
337                 ftp.UsePassive = true;
338                 _ftpResponse = (FtpWebResponse)ftp.GetResponse();
339                 Stream ftpStream = _ftpResponse.GetResponseStream();
340                 // ReSharper disable once PossibleNullReferenceException
341                 ftpStream.Close();
342                 _ftpResponse.Close();
343             }
344             catch (Exception)
345             {
346                 result = false;
347             }
348 
349             return result;
350         }
351 
352         /// <summary>
353         /// 删除文件
354         /// </summary>
355         /// <param name="fileName">文件名</param>
356         public bool DeleteFile(string fileName)
357         {
358             bool result = true;
359             FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(fileName);
360             ftp.Credentials = new NetworkCredential(_ftpName, _ftpPwd);
361             try
362             {
363                 ftp.Method = WebRequestMethods.Ftp.DeleteFile;
364                 ftp.UseBinary = true;
365                 ftp.UsePassive = true;
366                 _ftpResponse = (FtpWebResponse)ftp.GetResponse();
367                 Stream ftpStream = _ftpResponse.GetResponseStream();
368                 // ReSharper disable once PossibleNullReferenceException
369                 ftpStream.Close();
370                 _ftpResponse.Close();
371             }
372             catch (Exception)
373             {
374                 result = false;
375             }
376 
377             return result;
378         }
379 
380         /// <summary>
381         /// 创建目录
382         /// </summary>
383         /// <param name="dri"></param>
384         /// <returns></returns> 
385         public bool FtpMakeDir(string dri)
386         {
387             FtpWebRequest req = (FtpWebRequest)WebRequest.Create(dri);
388             req.Credentials = new NetworkCredential(_ftpName, _ftpPwd);
389             req.Method = WebRequestMethods.Ftp.MakeDirectory;
390             try
391             {
392                 FtpWebResponse response = (FtpWebResponse)req.GetResponse();
393                 response.Close();
394             }
395             catch (Exception)
396             {
397                 req.Abort();
398                 return false;
399             }
400             req.Abort();
401             return true;
402         }
403 
404         /// <summary>
405         /// 创建多级目录
406         /// </summary>
407         /// <param name="ftppath">目录,例如:/aaa/bbb/ccc </param>
408         public bool FtpMakeDirs(string ftppath)
409         {
410             string targetPath = _ftpUri;
411             var pathArray = ftppath.Split('/');
412 
413             try
414             {
415                 //遍历判断文件夹是否存在 
416                 foreach (var path in pathArray)
417                 {
418                     if (!string.IsNullOrEmpty(path.Trim()))
419                     {
420                         //不存在此层文件夹  
421                         if (!DirectoryExist(targetPath, path))
422                             FtpMakeDir(targetPath + "/" + path);
423 
424                         targetPath += "/" + path;
425                     }
426                 }
427             }
428             catch (Exception)
429             {
430                 return false;
431             }
432 
433             return true;
434         }
435 
436         /// <summary>
437         /// 下载
438         /// </summary>
439         /// <param name="fileName"></param>
440         public byte[] Download(string fileName)
441         {
442             byte[] buffer = null;
443             try
444             {
445                 // ReSharper disable once AccessToStaticMemberViaDerivedType
446                 var reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(_ftpUri + "/" + fileName));
447                 reqFtp.Method = WebRequestMethods.Ftp.DownloadFile;
448                 reqFtp.UseBinary = true;
449                 reqFtp.Credentials = new NetworkCredential(_ftpName, _ftpPwd);
450                 FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
451                 Stream ftpStream = response.GetResponseStream();
452                 int bufferSize = 51200; //Convert.ToInt32(GetFileSize(fileName)) + 51200;//
453                 buffer = new byte[bufferSize];
454                 // ReSharper disable once PossibleNullReferenceException
455                 var readCount = ftpStream.Read(buffer, 0, bufferSize);
456 
457                 while (readCount > 0)
458                 {
459                     readCount = ftpStream.Read(buffer, 0, bufferSize);
460                 }
461                 ftpStream.Close();
462                 response.Close();
463             }
464             catch (Exception)
465             {
466                 // ignored
467             }
468 
469             return buffer;
470         }
471 
472         /// <summary>
473         /// 获取当前目录下明细(包含文件和文件夹)
474         /// </summary>
475         /// <returns></returns>
476         public string[] GetFilesDetailList(string targetPath)
477         {
478             var tempftpUri = targetPath;
479 
480             try
481             {
482                 StringBuilder result = new StringBuilder();
483 
484                 Conn(tempftpUri);
485                 //获取 FTP 服务器上的文件的详细列表的 FTP LIST 协议方法
486                 _ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
487 
488                 WebResponse response = _ftpRequest.GetResponse();
489                 // ReSharper disable once AssignNullToNotNullAttribute
490                 StreamReader reader = new StreamReader(response.GetResponseStream());
491                 string line = reader.ReadLine();
492 
493                 while (line != null)
494                 {
495                     result.Append(line);
496                     result.Append("\n");
497                     line = reader.ReadLine();
498                 }
499 
500                 result.Remove(result.ToString().LastIndexOf("\n", StringComparison.Ordinal), 1);
501                 reader.Close();
502                 response.Close();
503 
504                 return result.ToString().Split('\n');
505             }
506             catch (Exception)
507             {
508                 var downloadFiles = new string[] { };
509                 return downloadFiles;
510             }
511         }
512 
513         /// <summary>
514         /// 获取当前目录下所有的文件夹列表(仅文件夹)
515         /// </summary>
516         /// <returns></returns>
517         public string[] GetDirectoryList(string targetPath)
518         {
519             string[] drectory = GetFilesDetailList(targetPath);
520             string m = "";
521             if (drectory != null && true & drectory.Any())
522             {
523                 foreach (string str in drectory)
524                 {
525                     int dirPos = str.IndexOf("<DIR>", StringComparison.Ordinal);
526                     if (dirPos > 0)
527                     {
528                         /*判断 Windows 风格*/
529                         m += str.Substring(dirPos + 5).Trim() + "\n";
530                     }
531                     else if (str.Trim().Substring(0, 1).ToUpper() == "D")
532                     {
533                         /*判断 Unix 风格*/
534                         string dir = str.Substring(56).Trim();
535                         if (dir != "." && dir != "..")
536                         {
537                             m += dir + "\n";
538                         }
539                     }
540                 }
541             }
542             char[] n = new char[] { '\n' };
543             return m.Split(n);
544         }
545 
546         /// <summary>
547         /// 判断当前目录下指定的子目录是否存在
548         /// modified at 2015/4/7 修改判断是否存在的方法,以前的方式过于臃肿,还有bug(竟然使用listdetail!)
549         /// </summary>
550         /// <param name="targetPath">服务器地址</param>
551         /// <param name="remoteDirectoryName">指定的目录名</param>
552         public bool DirectoryExist(string targetPath, string remoteDirectoryName)
553         {
554             try
555             {
556                 var uri = Path.Combine(targetPath, remoteDirectoryName).Replace(@"\", @"/");
557                 Conn(uri);
558                 _ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
559 
560                 using (var response = (FtpWebResponse)_ftpRequest.GetResponse())
561                 // ReSharper disable once AssignNullToNotNullAttribute
562                 // ReSharper disable once UnusedVariable
563                 using (var stream = new StreamReader(response.GetResponseStream()))
564                 {
565                 }
566                 return true;
567             }
568             catch (Exception)
569             {
570                 // ignored
571             }
572 
573             return false;
574         }
575 
576         /// <summary>
577         /// 获取指定文件大小
578         /// </summary>
579         /// <param name="filename"></param>
580         /// <returns></returns>
581         public long GetFileSize(string filename)
582         {
583             long fileSize = 0;
584             try
585             {
586                 // ReSharper disable once AccessToStaticMemberViaDerivedType
587                 var reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(_ftpUri + "/" + filename));
588 
589                 reqFtp.Method = WebRequestMethods.Ftp.GetFileSize;
590                 reqFtp.UseBinary = true;
591                 reqFtp.Credentials = new NetworkCredential(_ftpName, _ftpPwd);
592 
593                 FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
594                 Stream ftpStream = response.GetResponseStream();
595                 fileSize = response.ContentLength;
596 
597                 // ReSharper disable once PossibleNullReferenceException
598                 ftpStream.Close();
599                 response.Close();
600             }
601             catch (Exception)
602             {
603                 // ignored
604             }
605 
606             return fileSize;
607         }
608 
609         /// <summary>
610         /// 获取当前目录下文件列表(仅文件)
611         /// </summary>
612         /// <returns></returns>
613         public string[] GetFileList(string mask)
614         {
615             StringBuilder result = new StringBuilder();
616             try
617             {
618                 // ReSharper disable once AccessToStaticMemberViaDerivedType
619                 var reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(_ftpUri));
620                 reqFtp.UseBinary = true;
621                 reqFtp.Credentials = new NetworkCredential(_ftpName, _ftpPwd);
622                 reqFtp.Method = WebRequestMethods.Ftp.ListDirectory;
623                 WebResponse response = reqFtp.GetResponse();
624                 // ReSharper disable once AssignNullToNotNullAttribute
625                 StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
626 
627                 string line = reader.ReadLine();
628                 while (line != null)
629                 {
630                     if (mask.Trim() != string.Empty && mask.Trim() != "*.*")
631                     {
632                         var masks = mask.Substring(0, mask.IndexOf("*", StringComparison.Ordinal));
633                         if (line.Substring(0, masks.Length) == masks)
634                         {
635                             result.Append(line);
636                             result.Append("\n");
637                         }
638                     }
639                     else
640                     {
641                         result.Append(line);
642                         result.Append("\n");
643                     }
644                     line = reader.ReadLine();
645                 }
646                 result.Remove(result.ToString().LastIndexOf('\n'), 1);
647                 reader.Close();
648                 response.Close();
649                 return result.ToString().Split('\n');
650             }
651             catch (Exception ex)
652             {
653                 if (ex.Message.Trim() != "远程服务器返回错误: (550) 文件不可用(例如,未找到文件,无法访问文件)。")
654                 {
655                 }
656                 return null;
657             }
658         }
659 
660         /// <summary>
661         /// 判断文件是否存在
662         /// </summary>
663         /// <param name="filename"></param>
664         /// <returns></returns>
665         public bool FileExist(string filename)
666         {
667             bool result;
668             WebResponse response = null;
669             try
670             {
671                 WebRequest req = WebRequest.Create(filename);
672                 response = req.GetResponse();
673                 result = true;
674             }
675             catch (Exception)
676             {
677                 result = false;
678             }
679             finally
680             {
681                 response?.Close();
682             }
683 
684             return result;
685         }
686     }
687 }

 

Test:

1、创建多级目录:

 1             string targetPath = "ftp://192.168.1.148/";
 2             string ftpUserName = "ftpuser";
 3             string ftpPassword = "123456";
 4             
 5             var path = "1234/1234/1234";
 6             FtpHelper ftpHelper = new FtpHelper(targetPath , ftpUserName, ftpPassword);
 7             try
 8             {
 9                 ftpHelper.FtpMakeDirs(path);
10             }
11             catch (Exception ex)
12             {
13                 Console.Write(ex.Message);
14             }

 

转载于:https://www.cnblogs.com/LiuLiangXuan/p/6710070.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值