1. class DirectoryItem
  2. {
  3. public Uri BaseUri;
  4. public string AbsolutePath
  5. { get { return string.Format("{0}/{1}", BaseUri, Name); } }
  6. public DateTime DateCreated;
  7. public bool IsDirectory;
  8. public string Name;
  9. public List<DirectoryItem> Items;
  10. public override string ToString() { return Name; }
  11. }
  12.  
  13. internal enum enumFolderListFMT { UNIX, DOS_IIS };
  14. internal enum enumFTPPlatform { WindowsServer2008, ServU}
  15. /// <summary>
  16. /// 获取目录信息(包含文件夹,文件)
  17. /// </summary>
  18. /// <param name="address"></param>
  19. /// <param name="username"></param>
  20. /// <param name="password"></param>
  21. /// <returns></returns>
  22. static List<DirectoryItem> GetDirectoryInformation(string addr2, string username, string password)
  23. {
  24. var address = addr2.EndsWith("/") ? addr2.Substring(, addr2.Length - ) : addr2;//去除最后一个斜杠
  25. FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(address);
  26. request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
  27. request.Credentials = new NetworkCredential(username, password);
  28. request.UsePassive = true;
  29. request.UseBinary = true;
  30. request.KeepAlive = false;
  31.  
  32. string[] list = null;
  33. using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
  34. using (StreamReader reader = new StreamReader(response.GetResponseStream()))
  35. {
  36. list = reader.ReadToEnd().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
  37. }
  38.  
  39. //unix or dos_iis format?
  40. enumFolderListFMT folderFormat = enumFolderListFMT.UNIX;
  41. int dir_pos = ;
  42. bool found = false;
  43. foreach (var item in list)
  44. {
  45. if (item.ToLower().Contains("<dir>"))
  46. {
  47. folderFormat = enumFolderListFMT.DOS_IIS;
  48. dir_pos = item.ToLower().IndexOf("<dir>");
  49. found = true;
  50. break;
  51. }
  52. }
  53. if (!found && list.Length > && list[].ToLower()[] != 'd' && list[].ToLower()[] != '-')
  54. {
  55. folderFormat = enumFolderListFMT.DOS_IIS;
  56. }
  57.  
  58. enumFTPPlatform ftpPlatform = enumFTPPlatform.WindowsServer2008;
  59. if (folderFormat == enumFolderListFMT.UNIX)
  60. {
  61. if (list.Length > && list[].Substring(, ).ToLower().Count(c => c == '-') < )
  62. ftpPlatform = enumFTPPlatform.WindowsServer2008;
  63. else
  64. ftpPlatform = enumFTPPlatform.ServU;
  65. }
  66.  
  67. List<DirectoryItem> returnValue = new List<DirectoryItem>();
  68. if (folderFormat == enumFolderListFMT.DOS_IIS)
  69. {
  70. foreach (var item in list)
  71. {
  72. if (item.ToLower().Contains("<dir>"))
  73. {
  74. var dir = item.Substring(dir_pos + ).Trim();
  75. if (dir == "." || dir == "..") continue;
  76.  
  77. var di = new DirectoryItem();
  78. di.BaseUri = new Uri(address);
  79. //di.DateCreated = dateTime;
  80. di.IsDirectory = true;
  81. di.Name = dir;
  82. //Debug.WriteLine(di.AbsolutePath);
  83. di.Items = GetDirectoryInformation(di.AbsolutePath, username, password);
  84. returnValue.Add(di);
  85. }
  86. else
  87. {
  88. string filename = "";
  89. if(found)
  90. filename = item.Substring(dir_pos + ).Trim();
  91. else
  92. filename = item.Substring().Trim();
  93. var di = new DirectoryItem();
  94. di.BaseUri = new Uri(address);
  95. di.IsDirectory = false;
  96. di.Name = filename;
  97. di.Items = null;
  98. returnValue.Add(di);
  99. }
  100. }
  101. }
  102. else if (folderFormat == enumFolderListFMT.UNIX)
  103. {
  104. var pos = ftpPlatform == enumFTPPlatform.WindowsServer2008 ? : ;
  105. foreach (var item in list)
  106. {
  107. if (item.Substring(, ).ToLower() == "d")
  108. {
  109. var dir = item.Substring(pos).Trim();
  110. if (dir == "." || dir == "..") continue;
  111. var di = new DirectoryItem();
  112. di.BaseUri = new Uri(address);
  113. di.IsDirectory = true;
  114. di.Name = dir;
  115. di.Items = GetDirectoryInformation(di.AbsolutePath, username, password);
  116. returnValue.Add(di);
  117. }
  118. else if (item.Substring(, ).ToLower() == "-")
  119. {
  120. var filename = item.Substring(pos).Trim();
  121. var di = new DirectoryItem();
  122. di.BaseUri = new Uri(address);
  123. di.IsDirectory = false;
  124. di.Name = filename;
  125. di.Items = null;
  126. returnValue.Add(di);
  127. }
  128. }
  129. }
  130. return returnValue;
  131. }
  132.  
  133. /// <summary>
  134. /// 下载文件
  135. /// </summary>
  136. /// <param name="filePath">下载到哪里</param>
  137. /// <param name="outputFilename">下载后的文件名</param>
  138. /// <param name="fileName">服务器上的文件名</param>
  139. /// <param name="ftpServerIP">服务器全路径,注意最后的斜线不可少。如ftp://172.18.1.152:8009/aaa/</param>
  140. /// <param name="ftpUserID">访问的用户名</param>
  141. /// <param name="ftpPassword">访问的密码</param>
  142. /// <returns></returns>
  143. public int DownloadFile(string filePath, string outputFilename, string fileName, string ftpServerIP, string ftpUserID, string ftpPassword)
  144. {
  145. FtpWebRequest reqFTP;
  146. try
  147. {
  148. //filePath = < <The full path where the file is to be created.>>,
  149. //fileName = < <Name of the file to be created(Need not be the name of the file on FTP server).>>
  150. FileStream outputStream = new FileStream(filePath + "\\" + outputFilename, FileMode.Create);
  151.  
  152. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + fileName));
  153. reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
  154. reqFTP.UseBinary = true;
  155. reqFTP.KeepAlive = false;
  156. reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  157. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  158. Stream ftpStream = response.GetResponseStream();
  159. long cl = response.ContentLength;
  160. int bufferSize = ;
  161. int readCount;
  162. byte[] buffer = new byte[bufferSize];
  163.  
  164. readCount = ftpStream.Read(buffer, , bufferSize);
  165. while (readCount > )
  166. {
  167. outputStream.Write(buffer, , readCount);
  168. readCount = ftpStream.Read(buffer, , bufferSize);
  169. }
  170. ftpStream.Close();
  171. outputStream.Close();
  172. response.Close();
  173. return ;
  174. }
  175. catch (Exception ex)
  176. {
  177. // Logging.WriteError(ex.Message + ex.StackTrace);
  178. System.Windows.Forms.MessageBox.Show(ex.Message);
  179. return -;
  180. }
  181. }

get_directory_file_download

ftp_get_file_and_directory的更多相关文章

随机推荐

  1. Django: 之数据库导入、迁移和联用

    Django 数据库导入 从网上下载的一些数据,excel表格,xml文件,txt文件等有时候我们想把它导入数据库,应该如何操作呢? 以下操作符合 Django版本为 1.6 ,兼顾 Django 1 ...

  2. 性能更好的js动画实现方式---requestAnimationFrame

    用js来实现动画,我们一般是借助setTimeout或setInterval这两个函数,css3动画出来后,我们又可以使用css3来实现动画了,而且性能和流畅度也得到了很大的提升.但是css3动画还是 ...

  3. stock 财务 指标

    净资产收益率:"不能比利率低"每股收益是烟幕弹 有一点需要提请大家注意,观察净资产收益率至少要看过去三年的指标,如果公司没有经过大的资产重组,最好看看自其上市以来每一年的净资产收益 ...

  4. [转] Linux下移动virtualbox虚拟硬盘丢失eth0

    1.遇到什么的问题(What)      在新的virtualbox虚拟机上挂上曾使用过的虚拟硬盘,在启动的时候,发现找不到网卡eth0, 在输入ifconfig –a的时候,也没有任何Ethnet的 ...

  5. 总结OpenWrt系统基本操作方法

    1.OpenWrt系统编译好的固件位于哪个文件夹?root@ald888:/work/openwrt/trunk/bin/ramips# lsopenwrt-ramips-rt305x-mpr-a2- ...

  6. PAT (Advanced Level) 1052. Linked List Sorting (25)

    简单题. #include<iostream> #include<cstring> #include<cmath> #include<algorithm> ...

  7. 【BZOJ 1579】 1579: [Usaco2009 Feb]Revamping Trails 道路升级 (最短路)

    1579: [Usaco2009 Feb]Revamping Trails 道路升级 Description 每天,农夫John需要经过一些道路去检查牛棚N里面的牛. 农场上有M(1<=M< ...

  8. java实现webservice

    第一步:web工程--新建server-config.wsdd 文件与web.xml同级 其内容如下 <?xml version="1.0" encoding="U ...

  9. 基于Verilog HDL的ADC0809CCN数据采样

    本实验是用ADC0809CCN进行数据采样,并用7段数码管进行显示. ADC0809由一个8路模拟开关.一个地址锁存与译码器.一个A/D转换器和一个三态输出锁存器组成.多路开关可选通8个模拟通道,允许 ...

  10. 关于js的几道经典题(作用域、原型链等)自己做的

    1. function test() { var a = 1; setTimeout(function() { alert(a); a = 3; }, 1000); a = 2; setTimeout ...