erlchina 发表于 2015-5-27 06:39:02

FTP上传文件夹

文件上传类

1 using System;
2 using System.Collections.Generic;
3 using System.Diagnostics;
4 using System.IO;
5 using System.Linq;
6 using System.Net;
7 using System.Text;
8 using System.Threading.Tasks;
9
10 namespace ImageResize
11 {
12   public class FtpClient
13   {
14         public string ftpUser = string.Empty;
15         public string ftpPassword = string.Empty;
16         public string ftpRootURL = string.Empty;
17         public bool isFlag = true;
18         public string baseFolderPath = null;
19
20         public FtpClient(string url, string userid, string password)
21         {
22             this.ftpUser = userid;
23             this.ftpPassword = password;
24             this.ftpRootURL = url;
25         }
26
27         ///
28         /// 文件夹上传
29         ///
30         ///
31         /// ftpRootUrl + ftpPath
32         ///
33         public bool foldersUpload(string sourceFolder, string destFolder, string detailFolder)
34         {
35             bool isFolderFlag = false;
36             if (isFlag)
37             {
38               baseFolderPath = sourceFolder.Substring(0, sourceFolder.LastIndexOf("\\"));
39               isFlag = false;
40             }
41
42             string selectFolderName = sourceFolder.Replace(baseFolderPath, "").Replace("\\", "/");
43            
44             if (selectFolderName != null)
45             {
46               string ftpDirectory = destFolder + selectFolderName;
47               if (ftpDirectory.LastIndexOf('/') < ftpDirectory.Length - 1)
48               {
49                     ftpDirectory = ftpDirectory + "/";
50               }
51               if (!FtpDirectoryIsNotExists(ftpDirectory))
52               {
53                     CreateFtpDirectory(ftpDirectory);
54               }
55             }
56
57             try
58             {
59               string[] directories = Directory.EnumerateDirectories(sourceFolder).ToArray();
60               if (directories.Length > 0)
61               {
62                     foreach (string d in directories)
63                     {
64                         foldersUpload(d, destFolder, sourceFolder.Replace(baseFolderPath, "").Replace("\\","/"));
65                     }
66               }
67
68               string[] files = Directory.EnumerateFiles(sourceFolder).ToArray();
69               if (files.Length > 0)
70               {
71                     foreach (string s in files)
72                     {
73                        
74                         string fileName = s.Substring(s.LastIndexOf("\\")).Replace("\\", "/");
75
76                         if(selectFolderName.Contains("/"))
77                         {
78                            if(selectFolderName.LastIndexOf('/') < selectFolderName.Length -1)
79                            {
80                              selectFolderName = selectFolderName + '/';
81                            }
82                     
83                         }
84                         ftpRootURL = destFolder;
85
86                         fileUpload(new FileInfo(s), selectFolderName , fileName.Substring(1,fileName.Length -1));
87
88                     }
89               }
90               isFolderFlag = true;
91
92             }
93             catch (Exception ex)
94             {
95               Debug.WriteLine(ex.Message);
96             }
97             return isFolderFlag;
98         }
99
100
101         ///
102         /// 上传
103         ///
104         /// 本地文件绝对路径
105         /// 上传到ftp的路径
106         /// 上传到ftp的文件名
107         public bool fileUpload(FileInfo localFile, string ftpPath, string ftpFileName)
108         {
109             bool success = false;
110             FtpWebRequest ftpWebRequest = null;
111
112             FileStream localFileStream = null;
113             Stream requestStream = null;
114
115             try
116             {
117               // 检查FTP目标存放目录是否存在
118               // 1.1 ftp 上目标目录
119               string destFolderPath =ftpRootURL + ftpPath;
120
121               if (!FtpDirectoryIsNotExists(destFolderPath))
122               {
123                     CreateFtpDirectory(destFolderPath);
124               }
125
126               string uri = ftpRootURL + ftpPath + ftpFileName;
127               ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
128               ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
129               ftpWebRequest.UseBinary = true;
130
131               ftpWebRequest.KeepAlive = false;
132               ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;
133               ftpWebRequest.ContentLength = localFile.Length;
134
135               int buffLength = 2048;
136               byte[] buff = new byte;
137               int contentLen;
138
139               localFileStream = localFile.OpenRead();
140               requestStream = ftpWebRequest.GetRequestStream();
141
142               contentLen = localFileStream.Read(buff, 0, buffLength);
143               while (contentLen != 0)
144               {
145                     // 把内容从file stream 写入upload stream
146                     requestStream.Write(buff, 0, contentLen);
147                     contentLen = localFileStream.Read(buff, 0, buffLength);
148               }
149
150               success = true;
151             }
152             catch (Exception)
153             {
154               success = false;
155             }
156             finally
157             {
158               if (requestStream != null)
159               {
160                     requestStream.Close();
161               }
162               if (localFileStream != null)
163               {
164                     localFileStream.Close();
165               }
166             }
167
168             return success;
169         }
170
171
172         ///
173         /// 上传文件
174         ///
175         /// 本地文件地址(没有文件名)
176         /// 本地文件名
177         /// 上传到ftp的路径
178         /// 上传到ftp的文件名
179         public bool fileUpload(string localPath, string localFileName, string ftpPath, string ftpFileName)
180         {
181             bool success = false;
182             try
183             {
184               FileInfo localFile = new FileInfo(localPath + localFileName);
185               if (localFile.Exists)
186               {
187                     success = fileUpload(localFile, ftpPath, ftpFileName);
188               }
189               else
190               {
191                     success = false;
192               }
193             }
194             catch (Exception)
195             {
196               success = false;
197             }
198             return success;
199         }
200
201
202         ///
203         /// 下载文件
204         ///
205         /// 本地文件地址(没有文件名)
206         /// 本地文件名
207         /// 下载的ftp的路径
208         /// 下载的ftp的文件名
209         public bool fileDownload(string localPath, string localFileName, string ftpPath, string ftpFileName)
210         {
211             bool success = false;
212             FtpWebRequest ftpWebRequest = null;
213             FtpWebResponse ftpWebResponse = null;
214             Stream ftpResponseStream = null;
215             FileStream outputStream = null;
216             try
217             {
218               outputStream = new FileStream(localPath + localFileName, FileMode.Create);
219               string uri = ftpRootURL + ftpPath + ftpFileName;
220               ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
221               ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
222               ftpWebRequest.UseBinary = true;
223               ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;
224               ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
225               ftpResponseStream = ftpWebResponse.GetResponseStream();
226               long contentLength = ftpWebResponse.ContentLength;
227               int bufferSize = 2048;
228               byte[] buffer = new byte;
229               int readCount;
230               readCount = ftpResponseStream.Read(buffer, 0, bufferSize);
231               while (readCount > 0)
232               {
233                     outputStream.Write(buffer, 0, readCount);
234                     readCount = ftpResponseStream.Read(buffer, 0, bufferSize);
235               }
236               success = true;
237             }
238             catch (Exception)
239             {
240               success = false;
241             }
242             finally
243             {
244               if (outputStream != null)
245               {
246                     outputStream.Close();
247               }
248               if (ftpResponseStream != null)
249               {
250                     ftpResponseStream.Close();
251               }
252               if (ftpWebResponse != null)
253               {
254                     ftpWebResponse.Close();
255               }
256             }
257             return success;
258         }
259
260
261         ///
262         /// 重命名
263         ///
264         /// ftp文件路径
265         ///
266         ///
267         public bool fileRename(string ftpPath, string currentFileName, string newFileName)
268         {
269             bool success = false;
270             FtpWebRequest ftpWebRequest = null;
271             FtpWebResponse ftpWebResponse = null;
272             Stream ftpResponseStream = null;
273             try
274             {
275               string uri = ftpRootURL + ftpPath + currentFileName;
276               ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
277               ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
278               ftpWebRequest.UseBinary = true;
279               ftpWebRequest.Method = WebRequestMethods.Ftp.Rename;
280               ftpWebRequest.RenameTo = newFileName;
281
282               ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
283               ftpResponseStream = ftpWebResponse.GetResponseStream();
284
285             }
286             catch (Exception)
287             {
288               success = false;
289             }
290             finally
291             {
292               if (ftpResponseStream != null)
293               {
294                     ftpResponseStream.Close();
295               }
296               if (ftpWebResponse != null)
297               {
298                     ftpWebResponse.Close();
299               }
300             }
301             return success;
302         }
303
304
305         ///
306         /// 消除文件
307         ///
308         ///
309         public bool fileDelete(string ftpPath, string ftpName)
310         {
311             bool success = false;
312             FtpWebRequest ftpWebRequest = null;
313             FtpWebResponse ftpWebResponse = null;
314             Stream ftpResponseStream = null;
315             StreamReader streamReader = null;
316             try
317             {
318               string uri = ftpRootURL + ftpPath + ftpName;
319               ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
320               ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
321               ftpWebRequest.KeepAlive = false;
322               ftpWebRequest.Method = WebRequestMethods.Ftp.DeleteFile;
323               ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
324               long size = ftpWebResponse.ContentLength;
325               ftpResponseStream = ftpWebResponse.GetResponseStream();
326               streamReader = new StreamReader(ftpResponseStream);
327               string result = String.Empty;
328               result = streamReader.ReadToEnd();
329
330               success = true;
331             }
332             catch (Exception)
333             {
334               success = false;
335             }
336             finally
337             {
338               if (streamReader != null)
339               {
340                     streamReader.Close();
341               }
342               if (ftpResponseStream != null)
343               {
344                     ftpResponseStream.Close();
345               }
346               if (ftpWebResponse != null)
347               {
348                     ftpWebResponse.Close();
349               }
350             }
351             return success;
352         }
353
354         ///
355         /// 文件存在检查
356         ///
357         public bool fileCheckExist(string destFolderPath, string fileName)
358         {
359             bool success = false;
360             FtpWebRequest ftpWebRequest = null;
361             WebResponse webResponse = null;
362             StreamReader reader = null;
363             try
364             {
365
366
367               ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(destFolderPath));
368               ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
369               ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectory;
370               ftpWebRequest.KeepAlive = false;
371               webResponse = ftpWebRequest.GetResponse();
372               reader = new StreamReader(webResponse.GetResponseStream());
373               string line = reader.ReadLine();
374               while (line != null)
375               {
376                     string ftpName = "test.jpg";
377                     if (line == ftpName)
378                     {
379                         success = true;
380                         break;
381                     }
382                     line = reader.ReadLine();
383               }
384             }
385             catch (Exception)
386             {
387               success = false;
388             }
389             finally
390             {
391               if (reader != null)
392               {
393                     reader.Close();
394               }
395               if (webResponse != null)
396               {
397                     webResponse.Close();
398               }
399             }
400             return success;
401         }
402
403      
404         ///
405         /// 创建FTP文件目录
406         ///
407         /// ftp服务器上的文件目录
408         public void CreateFtpDirectory(string ftpDirectory)
409         {
410             try
411             {
412               FtpWebRequest ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpDirectory));
413               ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
414               ftpWebRequest.UseBinary = true;
415               ftpWebRequest.KeepAlive = false;
416               ftpWebRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
417
418               FtpWebResponse respFTP = (FtpWebResponse)ftpWebRequest.GetResponse();
419               respFTP.Close();
420             }
421             catch (Exception ex)
422             {
423               Debug.WriteLine("FTP创建目录失败" + ex.Message);
424             }
425
426         }
427
428
429
430
431         ///
432         /// 获取目录下的详细信息
433         ///
434         /// 本机目录
435         ///
436         public List GetDirDetails(string localDir)
437         {
438             List infos = new List();
439             try
440             {
441               infos.Add(Directory.GetFiles(localDir).ToList());
442               infos.Add(Directory.GetDirectories(localDir).ToList());
443               for (int i = 0; i < infos.Count; i++)
444               {
445                     int index = infos.LastIndexOf(@"\");
446                     infos = infos.Substring(index + 1);
447               }
448             }
449             catch(Exception ex)
450             {
451               Debug.WriteLine(ex.Message);
452             }
453             return infos;
454         }
455
456
457         public void UploadDirectory(string localDir, string ftpPath, string dirName, string ftpUser, string ftpPassword)
458         {
459             if (ftpUser == null)
460             {
461               ftpUser = "";
462             }
463             if (ftpPassword == null)
464             {
465               ftpPassword = "";
466             }
467
468             string dir = localDir + dirName + @"\";
469
470             if (!Directory.Exists(dir))
471             {
472               return;
473             }
474
475             //if (!CheckDirectoryExist(ftpPath, dirName))
476             //{
477             //    MakeDir(ftpPath, dirName);
478            
479             //}
480
481             List infos = GetDirDetails(dir); //获取当前目录下的所有文件和文件夹
482             //先上传文件
483         //    MyLog.ShowMessage(dir + "下的文件数:" + infos.Count.ToString());
484             for (int i = 0; i < infos.Count; i++)
485             {
486               Console.WriteLine(infos);
487            //   UpLoadFile(dir + infos, ftpPath + dirName + @"/" + infos, ftpUser, ftpPassword);
488             }
489             //再处理文件夹
490         //MyLog.ShowMessage(dir + "下的目录数:" + infos.Count.ToString());
491             for (int i = 0; i < infos.Count; i++)
492             {
493               UploadDirectory(dir, ftpPath + dirName + @"/", infos, ftpUser, ftpPassword);
494             }
495         }
496
497         ///
498         /// 判断Ftp上待上传文件存放的(文件夹)目录是否存在
499         /// 注意事项:目录结构的最后一个字符一定要是一个斜杠
500         ///
501         /// Ftp服务器上存放待上传文件的目录
502         privatebool FtpDirectoryIsNotExists(string destFolderPath)
503         {
504             try
505             {
506               var request = (FtpWebRequest)WebRequest.Create(destFolderPath);
507               request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
508               request.Method = WebRequestMethods.Ftp.ListDirectory;
509               FtpWebResponse response = (FtpWebResponse)request.GetResponse();
510             }
511             catch (WebException ex)
512             {
513               FtpWebResponse response = (FtpWebResponse)ex.Response;
514               if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
515               {
516                     response.Close();
517                     return false;
518               }
519               else
520               {
521                     response.Close();
522               }
523             }
524             return true;
525         }
526
527         ///
528         /// 解析文件所在的路径(即当前文件所在的文件位置)
529         ///
530         /// 需要存储在FTP服务器上的文件路径,如:ftp://192.168.1.100/LocalUser/picture1.jpg
531         ///
532         public string FtpParseDirectory(string destFilePath)
533         {
534             return destFilePath.Substring(0, destFilePath.LastIndexOf("/"));
535         }
536
537
538         // 验证文件类型
539         public bool IsAllowableFileType(string fileName)
540         {
541             //从web.config读取判断文件类型限制
542             string stringstrFileTypeLimit = string.Format(".jpeg|*.jpeg|*.*|All Files");
543             //当前文件扩展名是否包含在这个字符串中
544             if (stringstrFileTypeLimit.IndexOf(fileName.ToLower()) != -1)
545             {
546               return true;
547             }
548             else
549             {
550               return false;
551             }
552         }
553
554         //文件大小
555         public bool IsAllowableFileSize(long FileContentLength)
556         {
557             //从web.config读取判断文件大小的限制
558             Int32 doubleiFileSizeLimit = 1232;
559
560             //判断文件是否超出了限制
561             if (doubleiFileSizeLimit > FileContentLength)
562             {
563               return true;
564             }
565             else
566             {
567               return false;
568             }
569         }
570
571
572
573   }
574 }
  
页: [1]
查看完整版本: FTP上传文件夹