设为首页 收藏本站
查看: 936|回复: 0

FTP上传文件夹

[复制链接]

尚未签到

发表于 2015-5-27 06:39:02 | 显示全部楼层 |阅读模式
文件上传类

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[buffLength];
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[bufferSize];
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[0].Count; i++)
444                 {
445                     int index = infos[1].LastIndexOf(@"\");
446                     infos[1] = infos[1].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[0].Count.ToString());
484             for (int i = 0; i < infos[0].Count; i++)
485             {
486                 Console.WriteLine(infos[0]);
487              //   UpLoadFile(dir + infos[0], ftpPath + dirName + @"/" + infos[0], ftpUser, ftpPassword);
488             }
489             //再处理文件夹
490           //  MyLog.ShowMessage(dir + "下的目录数:" + infos[1].Count.ToString());
491             for (int i = 0; i < infos[1].Count; i++)
492             {
493                 UploadDirectory(dir, ftpPath + dirName + @"/", infos[1], ftpUser, ftpPassword);
494             }
495         }
496
497         ///
498         /// 判断Ftp上待上传文件存放的(文件夹)目录是否存在
499         /// 注意事项:目录结构的最后一个字符一定要是一个斜杠
500         ///
501         /// Ftp服务器上存放待上传文件的目录
502         private  bool 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、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-70973-1-1.html 上篇帖子: 在Win7中用ftp的方法 下篇帖子: FTP组件edtFTPj
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表