FTPHelper.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.IO;
  5. using System.Net;
  6. using System.Text.RegularExpressions;
  7. namespace Ant.Service.Utilities
  8. {
  9. public class FTPHelper
  10. {
  11. #region 字段
  12. string ftpURI;
  13. string ftpUserID;
  14. string ftpServerIP;
  15. string ftpPassword;
  16. string ftpRemotePath;
  17. #endregion
  18. /// <summary>
  19. /// 连接FTP服务器
  20. /// </summary>
  21. /// <param name="FtpServerIP">FTP连接地址</param>
  22. /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>
  23. /// <param name="FtpUserID">用户名</param>
  24. /// <param name="FtpPassword">密码</param>
  25. public FTPHelper(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
  26. {
  27. ftpServerIP = FtpServerIP;
  28. ftpRemotePath = FtpRemotePath;
  29. ftpUserID = FtpUserID;
  30. ftpPassword = FtpPassword;
  31. ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
  32. }
  33. /// <summary>
  34. /// 上传
  35. /// </summary>
  36. public void Upload(string filename)
  37. {
  38. FileInfo fileInf = new FileInfo(filename);
  39. FtpWebRequest reqFTP;
  40. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileInf.Name));
  41. reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  42. reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
  43. reqFTP.KeepAlive = false;
  44. reqFTP.UseBinary = true;
  45. reqFTP.ContentLength = fileInf.Length;
  46. int buffLength = 2048;
  47. byte[] buff = new byte[buffLength];
  48. int contentLen;
  49. FileStream fs = fileInf.OpenRead();
  50. try
  51. {
  52. Stream strm = reqFTP.GetRequestStream();
  53. contentLen = fs.Read(buff, 0, buffLength);
  54. while (contentLen != 0)
  55. {
  56. strm.Write(buff, 0, contentLen);
  57. contentLen = fs.Read(buff, 0, buffLength);
  58. }
  59. strm.Close();
  60. fs.Close();
  61. }
  62. catch (Exception ex)
  63. {
  64. throw new Exception(ex.Message);
  65. }
  66. }
  67. /// <summary>
  68. /// 下载
  69. /// </summary>
  70. public void Download(string filePath, string fileName)
  71. {
  72. try
  73. {
  74. FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
  75. FtpWebRequest reqFTP;
  76. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
  77. reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  78. reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
  79. reqFTP.UseBinary = true;
  80. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  81. Stream ftpStream = response.GetResponseStream();
  82. long cl = response.ContentLength;
  83. int bufferSize = 2048;
  84. int readCount;
  85. byte[] buffer = new byte[bufferSize];
  86. readCount = ftpStream.Read(buffer, 0, bufferSize);
  87. while (readCount > 0)
  88. {
  89. outputStream.Write(buffer, 0, readCount);
  90. readCount = ftpStream.Read(buffer, 0, bufferSize);
  91. }
  92. ftpStream.Close();
  93. outputStream.Close();
  94. response.Close();
  95. }
  96. catch (Exception ex)
  97. {
  98. throw new Exception(ex.Message);
  99. }
  100. }
  101. /// <summary>
  102. /// 删除文件
  103. /// </summary>
  104. public void Delete(string fileName)
  105. {
  106. try
  107. {
  108. FtpWebRequest reqFTP;
  109. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
  110. reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  111. reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
  112. reqFTP.KeepAlive = false;
  113. string result = String.Empty;
  114. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  115. long size = response.ContentLength;
  116. Stream datastream = response.GetResponseStream();
  117. StreamReader sr = new StreamReader(datastream);
  118. result = sr.ReadToEnd();
  119. sr.Close();
  120. datastream.Close();
  121. response.Close();
  122. }
  123. catch (Exception ex)
  124. {
  125. throw new Exception(ex.Message);
  126. }
  127. }
  128. /// <summary>
  129. /// 获取当前目录下明细(包含文件和文件夹)
  130. /// </summary>
  131. public string[] GetFilesDetailList()
  132. {
  133. try
  134. {
  135. StringBuilder result = new StringBuilder();
  136. FtpWebRequest ftp;
  137. ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
  138. ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  139. ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
  140. WebResponse response = ftp.GetResponse();
  141. StreamReader reader = new StreamReader(response.GetResponseStream());
  142. string line = reader.ReadLine();
  143. line = reader.ReadLine();
  144. line = reader.ReadLine();
  145. while (line != null)
  146. {
  147. result.Append(line);
  148. result.Append("\n");
  149. line = reader.ReadLine();
  150. }
  151. result.Remove(result.ToString().LastIndexOf("\n"), 1);
  152. reader.Close();
  153. response.Close();
  154. return result.ToString().Split('\n');
  155. }
  156. catch (Exception ex)
  157. {
  158. throw new Exception(ex.Message);
  159. }
  160. }
  161. /// <summary>
  162. /// 获取FTP文件列表(包括文件夹)
  163. /// </summary>
  164. private string[] GetAllList(string url)
  165. {
  166. List<string> list = new List<string>();
  167. FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri(url));
  168. req.Credentials = new NetworkCredential(ftpPassword, ftpPassword);
  169. req.Method = WebRequestMethods.Ftp.ListDirectory;
  170. req.UseBinary = true;
  171. req.UsePassive = true;
  172. try
  173. {
  174. using (FtpWebResponse res = (FtpWebResponse)req.GetResponse())
  175. {
  176. using (StreamReader sr = new StreamReader(res.GetResponseStream()))
  177. {
  178. string s;
  179. while ((s = sr.ReadLine()) != null)
  180. {
  181. list.Add(s);
  182. }
  183. }
  184. }
  185. }
  186. catch (Exception ex)
  187. {
  188. throw (ex);
  189. }
  190. return list.ToArray();
  191. }
  192. /// <summary>
  193. /// 获取当前目录下文件列表(不包括文件夹)
  194. /// </summary>
  195. public string[] GetFileList(string url)
  196. {
  197. StringBuilder result = new StringBuilder();
  198. FtpWebRequest reqFTP;
  199. try
  200. {
  201. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
  202. reqFTP.UseBinary = true;
  203. reqFTP.Credentials = new NetworkCredential(ftpPassword, ftpPassword);
  204. reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
  205. WebResponse response = reqFTP.GetResponse();
  206. StreamReader reader = new StreamReader(response.GetResponseStream());
  207. string line = reader.ReadLine();
  208. while (line != null)
  209. {
  210. if (line.IndexOf("<DIR>") == -1)
  211. {
  212. result.Append(Regex.Match(line, @"[\S]+ [\S]+", RegexOptions.IgnoreCase).Value.Split(' ')[1]);
  213. result.Append("\n");
  214. }
  215. line = reader.ReadLine();
  216. }
  217. result.Remove(result.ToString().LastIndexOf('\n'), 1);
  218. reader.Close();
  219. response.Close();
  220. }
  221. catch (Exception ex)
  222. {
  223. throw (ex);
  224. }
  225. return result.ToString().Split('\n');
  226. }
  227. /// <summary>
  228. /// 判断当前目录下指定的文件是否存在
  229. /// </summary>
  230. /// <param name="RemoteFileName">远程文件名</param>
  231. public bool FileExist(string RemoteFileName)
  232. {
  233. string[] fileList = GetFileList("*.*");
  234. foreach (string str in fileList)
  235. {
  236. if (str.Trim() == RemoteFileName.Trim())
  237. {
  238. return true;
  239. }
  240. }
  241. return false;
  242. }
  243. /// <summary>
  244. /// 创建文件夹
  245. /// </summary>
  246. public void MakeDir(string dirName)
  247. {
  248. FtpWebRequest reqFTP;
  249. try
  250. {
  251. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
  252. reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
  253. reqFTP.UseBinary = true;
  254. reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  255. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  256. Stream ftpStream = response.GetResponseStream();
  257. ftpStream.Close();
  258. response.Close();
  259. }
  260. catch (Exception ex)
  261. { }
  262. }
  263. /// <summary>
  264. /// 获取指定文件大小
  265. /// </summary>
  266. public long GetFileSize(string filename)
  267. {
  268. FtpWebRequest reqFTP;
  269. long fileSize = 0;
  270. try
  271. {
  272. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
  273. reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
  274. reqFTP.UseBinary = true;
  275. reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  276. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  277. Stream ftpStream = response.GetResponseStream();
  278. fileSize = response.ContentLength;
  279. ftpStream.Close();
  280. response.Close();
  281. }
  282. catch (Exception ex)
  283. { }
  284. return fileSize;
  285. }
  286. /// <summary>
  287. /// 更改文件名
  288. /// </summary>
  289. public void ReName(string currentFilename, string newFilename)
  290. {
  291. FtpWebRequest reqFTP;
  292. try
  293. {
  294. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename));
  295. reqFTP.Method = WebRequestMethods.Ftp.Rename;
  296. reqFTP.RenameTo = newFilename;
  297. reqFTP.UseBinary = true;
  298. reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  299. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  300. Stream ftpStream = response.GetResponseStream();
  301. ftpStream.Close();
  302. response.Close();
  303. }
  304. catch (Exception ex)
  305. { }
  306. }
  307. /// <summary>
  308. /// 移动文件
  309. /// </summary>
  310. public void MovieFile(string currentFilename, string newDirectory)
  311. {
  312. ReName(currentFilename, newDirectory);
  313. }
  314. /// <summary>
  315. /// 切换当前目录
  316. /// </summary>
  317. /// <param name="IsRoot">true:绝对路径 false:相对路径</param>
  318. public void GotoDirectory(string DirectoryName, bool IsRoot)
  319. {
  320. if (IsRoot)
  321. {
  322. ftpRemotePath = DirectoryName;
  323. }
  324. else
  325. {
  326. ftpRemotePath += DirectoryName + "/";
  327. }
  328. ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
  329. }
  330. }
  331. }