查看: 2331|回复: 0

[.NET开发] C# FTP操作类分享

发表于 2018-2-9 08:00:00

本文实例为大家分享了C# FTP操作类的具体代码,可进行FTP的上传,下载等其他功能,支持断点续传,供大家参考,具体内容如下

FTPHelper

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace ManagementProject
  9. {
  10. public class FTPHelper
  11. {
  12. string ftpRemotePath;
  13. #region 变量属性
  14. /// <summary>
  15. /// Ftp服务器ip
  16. /// </summary>
  17. public static string FtpServerIP = "";
  18. /// <summary>
  19. /// Ftp 指定用户名
  20. /// </summary>
  21. public static string FtpUserID = "";
  22. /// <summary>
  23. /// Ftp 指定用户密码
  24. /// </summary>
  25. public static string FtpPassword = "";
  26. public static string ftpURI = "ftp://" + FtpServerIP + "/";
  27. #endregion
  28. #region 从FTP服务器下载文件,指定本地路径和本地文件名
  29. /// <summary>
  30. /// 从FTP服务器下载文件,指定本地路径和本地文件名
  31. /// </summary>
  32. /// <param name="remoteFileName">远程文件名</param>
  33. /// <param name="localFileName">保存本地的文件名(包含路径)</param>
  34. /// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
  35. /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
  36. /// <returns>是否下载成功</returns>
  37. public static bool FtpDownload(string remoteFileName, string localFileName, bool ifCredential, Action<int, int> updateProgress = null)
  38. {
  39. FtpWebRequest reqFTP, ftpsize;
  40. Stream ftpStream = null;
  41. FtpWebResponse response = null;
  42. FileStream outputStream = null;
  43. try
  44. {
  45. outputStream = new FileStream(localFileName, FileMode.Create);
  46. if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)
  47. {
  48. throw new Exception("ftp下载目标服务器地址未设置!");
  49. }
  50. Uri uri = new Uri("ftp://" + FtpServerIP + "/" + remoteFileName);
  51. ftpsize = (FtpWebRequest)FtpWebRequest.Create(uri);
  52. ftpsize.UseBinary = true;
  53. reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
  54. reqFTP.UseBinary = true;
  55. reqFTP.KeepAlive = false;
  56. if (ifCredential)//使用用户身份认证
  57. {
  58. ftpsize.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
  59. reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
  60. }
  61. ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
  62. FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse();
  63. long totalBytes = re.ContentLength;
  64. re.Close();
  65. reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
  66. response = (FtpWebResponse)reqFTP.GetResponse();
  67. ftpStream = response.GetResponseStream();
  68. //更新进度
  69. if (updateProgress != null)
  70. {
  71. updateProgress((int)totalBytes, 0);//更新进度条
  72. }
  73. long totalDownloadedByte = 0;
  74. int bufferSize = 2048;
  75. int readCount;
  76. byte[] buffer = new byte[bufferSize];
  77. readCount = ftpStream.Read(buffer, 0, bufferSize);
  78. while (readCount > 0)
  79. {
  80. totalDownloadedByte = readCount + totalDownloadedByte;
  81. outputStream.Write(buffer, 0, readCount);
  82. //更新进度
  83. if (updateProgress != null)
  84. {
  85. updateProgress((int)totalBytes, (int)totalDownloadedByte);//更新进度条
  86. }
  87. readCount = ftpStream.Read(buffer, 0, bufferSize);
  88. }
  89. ftpStream.Close();
  90. outputStream.Close();
  91. response.Close();
  92. return true;
  93. }
  94. catch (Exception ex)
  95. {
  96. return false;
  97. throw;
  98. }
  99. finally
  100. {
  101. if (ftpStream != null)
  102. {
  103. ftpStream.Close();
  104. }
  105. if (outputStream != null)
  106. {
  107. outputStream.Close();
  108. }
  109. if (response != null)
  110. {
  111. response.Close();
  112. }
  113. }
  114. }
  115. /// <summary>
  116. /// 从FTP服务器下载文件,指定本地路径和本地文件名(支持断点下载)
  117. /// </summary>
  118. /// <param name="remoteFileName">远程文件名</param>
  119. /// <param name="localFileName">保存本地的文件名(包含路径)</param>
  120. /// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
  121. /// <param name="size">已下载文件流大小</param>
  122. /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
  123. /// <returns>是否下载成功</returns>
  124. public static bool FtpBrokenDownload(string remoteFileName, string localFileName, bool ifCredential, long size, Action<int, int> updateProgress = null)
  125. {
  126. FtpWebRequest reqFTP, ftpsize;
  127. Stream ftpStream = null;
  128. FtpWebResponse response = null;
  129. FileStream outputStream = null;
  130. try
  131. {
  132. outputStream = new FileStream(localFileName, FileMode.Append);
  133. if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)
  134. {
  135. throw new Exception("ftp下载目标服务器地址未设置!");
  136. }
  137. Uri uri = new Uri("ftp://" + FtpServerIP + "/" + remoteFileName);
  138. ftpsize = (FtpWebRequest)FtpWebRequest.Create(uri);
  139. ftpsize.UseBinary = true;
  140. ftpsize.ContentOffset = size;
  141. reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
  142. reqFTP.UseBinary = true;
  143. reqFTP.KeepAlive = false;
  144. reqFTP.ContentOffset = size;
  145. if (ifCredential)//使用用户身份认证
  146. {
  147. ftpsize.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
  148. reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
  149. }
  150. ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
  151. FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse();
  152. long totalBytes = re.ContentLength;
  153. re.Close();
  154. reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
  155. response = (FtpWebResponse)reqFTP.GetResponse();
  156. ftpStream = response.GetResponseStream();
  157. //更新进度
  158. if (updateProgress != null)
  159. {
  160. updateProgress((int)totalBytes, 0);//更新进度条
  161. }
  162. long totalDownloadedByte = 0;
  163. int bufferSize = 2048;
  164. int readCount;
  165. byte[] buffer = new byte[bufferSize];
  166. readCount = ftpStream.Read(buffer, 0, bufferSize);
  167. while (readCount > 0)
  168. {
  169. totalDownloadedByte = readCount + totalDownloadedByte;
  170. outputStream.Write(buffer, 0, readCount);
  171. //更新进度
  172. if (updateProgress != null)
  173. {
  174. updateProgress((int)totalBytes, (int)totalDownloadedByte);//更新进度条
  175. }
  176. readCount = ftpStream.Read(buffer, 0, bufferSize);
  177. }
  178. ftpStream.Close();
  179. outputStream.Close();
  180. response.Close();
  181. return true;
  182. }
  183. catch (Exception ex)
  184. {
  185. return false;
  186. throw;
  187. }
  188. finally
  189. {
  190. if (ftpStream != null)
  191. {
  192. ftpStream.Close();
  193. }
  194. if (outputStream != null)
  195. {
  196. outputStream.Close();
  197. }
  198. if (response != null)
  199. {
  200. response.Close();
  201. }
  202. }
  203. }
  204. /// <summary>
  205. /// 从FTP服务器下载文件,指定本地路径和本地文件名
  206. /// </summary>
  207. /// <param name="remoteFileName">远程文件名</param>
  208. /// <param name="localFileName">保存本地的文件名(包含路径)</param>
  209. /// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
  210. /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
  211. /// <param name="brokenOpen">是否断点下载:true 会在localFileName 找是否存在已经下载的文件,并计算文件流大小</param>
  212. /// <returns>是否下载成功</returns>
  213. public static bool FtpDownload(string remoteFileName, string localFileName, bool ifCredential, bool brokenOpen, Action<int, int> updateProgress = null)
  214. {
  215. if (brokenOpen)
  216. {
  217. try
  218. {
  219. long size = 0;
  220. if (File.Exists(localFileName))
  221. {
  222. using (FileStream outputStream = new FileStream(localFileName, FileMode.Open))
  223. {
  224. size = outputStream.Length;
  225. }
  226. }
  227. return FtpBrokenDownload(remoteFileName, localFileName, ifCredential, size, updateProgress);
  228. }
  229. catch
  230. {
  231. throw;
  232. }
  233. }
  234. else
  235. {
  236. return FtpDownload(remoteFileName, localFileName, ifCredential, updateProgress);
  237. }
  238. }
  239. #endregion
  240. #region 上传文件到FTP服务器
  241. /// <summary>
  242. /// 上传文件到FTP服务器
  243. /// </summary>
  244. /// <param name="localFullPath">本地带有完整路径的文件名</param>
  245. /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
  246. /// <returns>是否下载成功</returns>
  247. public static bool FtpUploadFile(string localFullPathName, Action<int, int> updateProgress = null)
  248. {
  249. FtpWebRequest reqFTP;
  250. Stream stream = null;
  251. FtpWebResponse response = null;
  252. FileStream fs = null;
  253. try
  254. {
  255. FileInfo finfo = new FileInfo(localFullPathName);
  256. if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)
  257. {
  258. throw new Exception("ftp上传目标服务器地址未设置!");
  259. }
  260. Uri uri = new Uri("ftp://" + FtpServerIP + "/" + finfo.Name);
  261. reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
  262. reqFTP.KeepAlive = false;
  263. reqFTP.UseBinary = true;
  264. reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);//用户,密码
  265. reqFTP.Method = WebRequestMethods.Ftp.UploadFile;//向服务器发出下载请求命令
  266. reqFTP.ContentLength = finfo.Length;//为request指定上传文件的大小
  267. response = reqFTP.GetResponse() as FtpWebResponse;
  268. reqFTP.ContentLength = finfo.Length;
  269. int buffLength = 1024;
  270. byte[] buff = new byte[buffLength];
  271. int contentLen;
  272. fs = finfo.OpenRead();
  273. stream = reqFTP.GetRequestStream();
  274. contentLen = fs.Read(buff, 0, buffLength);
  275. int allbye = (int)finfo.Length;
  276. //更新进度
  277. if (updateProgress != null)
  278. {
  279. updateProgress((int)allbye, 0);//更新进度条
  280. }
  281. int startbye = 0;
  282. while (contentLen != 0)
  283. {
  284. startbye = contentLen + startbye;
  285. stream.Write(buff, 0, contentLen);
  286. //更新进度
  287. if (updateProgress != null)
  288. {
  289. updateProgress((int)allbye, (int)startbye);//更新进度条
  290. }
  291. contentLen = fs.Read(buff, 0, buffLength);
  292. }
  293. stream.Close();
  294. fs.Close();
  295. response.Close();
  296. return true;
  297. }
  298. catch (Exception ex)
  299. {
  300. return false;
  301. throw;
  302. }
  303. finally
  304. {
  305. if (fs != null)
  306. {
  307. fs.Close();
  308. }
  309. if (stream != null)
  310. {
  311. stream.Close();
  312. }
  313. if (response != null)
  314. {
  315. response.Close();
  316. }
  317. }
  318. }
  319. /// <summary>
  320. /// 上传文件到FTP服务器(断点续传)
  321. /// </summary>
  322. /// <param name="localFullPath">本地文件全路径名称:C:\Users\JianKunKing\Desktop\IronPython脚本测试工具</param>
  323. /// <param name="remoteFilepath">远程文件所在文件夹路径</param>
  324. /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
  325. /// <returns></returns>
  326. public static bool FtpUploadBroken(string localFullPath, string remoteFilepath, Action<int, int> updateProgress = null)
  327. {
  328. if (remoteFilepath == null)
  329. {
  330. remoteFilepath = "";
  331. }
  332. string newFileName = string.Empty;
  333. bool success = true;
  334. FileInfo fileInf = new FileInfo(localFullPath);
  335. long allbye = (long)fileInf.Length;
  336. if (fileInf.Name.IndexOf("#") == -1)
  337. {
  338. newFileName = RemoveSpaces(fileInf.Name);
  339. }
  340. else
  341. {
  342. newFileName = fileInf.Name.Replace("#", "#");
  343. newFileName = RemoveSpaces(newFileName);
  344. }
  345. long startfilesize = GetFileSize(newFileName, remoteFilepath);
  346. if (startfilesize >= allbye)
  347. {
  348. return false;
  349. }
  350. long startbye = startfilesize;
  351. //更新进度
  352. if (updateProgress != null)
  353. {
  354. updateProgress((int)allbye, (int)startfilesize);//更新进度条
  355. }
  356. string uri;
  357. if (remoteFilepath.Length == 0)
  358. {
  359. uri = "ftp://" + FtpServerIP + "/" + newFileName;
  360. }
  361. else
  362. {
  363. uri = "ftp://" + FtpServerIP + "/" + remoteFilepath + "/" + newFileName;
  364. }
  365. FtpWebRequest reqFTP;
  366. // 根据uri创建FtpWebRequest对象
  367. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
  368. // ftp用户名和密码
  369. reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
  370. // 默认为true,连接不会被关闭
  371. // 在一个命令之后被执行
  372. reqFTP.KeepAlive = false;
  373. // 指定执行什么命令
  374. reqFTP.Method = WebRequestMethods.Ftp.AppendFile;
  375. // 指定数据传输类型
  376. reqFTP.UseBinary = true;
  377. // 上传文件时通知服务器文件的大小
  378. reqFTP.ContentLength = fileInf.Length;
  379. int buffLength = 2048;// 缓冲大小设置为2kb
  380. byte[] buff = new byte[buffLength];
  381. // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
  382. FileStream fs = fileInf.OpenRead();
  383. Stream strm = null;
  384. try
  385. {
  386. // 把上传的文件写入流
  387. strm = reqFTP.GetRequestStream();
  388. // 每次读文件流的2kb
  389. fs.Seek(startfilesize, 0);
  390. int contentLen = fs.Read(buff, 0, buffLength);
  391. // 流内容没有结束
  392. while (contentLen != 0)
  393. {
  394. // 把内容从file stream 写入 upload stream
  395. strm.Write(buff, 0, contentLen);
  396. contentLen = fs.Read(buff, 0, buffLength);
  397. startbye += contentLen;
  398. //更新进度
  399. if (updateProgress != null)
  400. {
  401. updateProgress((int)allbye, (int)startbye);//更新进度条
  402. }
  403. }
  404. // 关闭两个流
  405. strm.Close();
  406. fs.Close();
  407. }
  408. catch
  409. {
  410. success = false;
  411. throw;
  412. }
  413. finally
  414. {
  415. if (fs != null)
  416. {
  417. fs.Close();
  418. }
  419. if (strm != null)
  420. {
  421. strm.Close();
  422. }
  423. }
  424. return success;
  425. }
  426. /// <summary>
  427. /// 去除空格
  428. /// </summary>
  429. /// <param name="str"></param>
  430. /// <returns></returns>
  431. private static string RemoveSpaces(string str)
  432. {
  433. string a = "";
  434. CharEnumerator CEnumerator = str.GetEnumerator();
  435. while (CEnumerator.MoveNext())
  436. {
  437. byte[] array = new byte[1];
  438. array = System.Text.Encoding.ASCII.GetBytes(CEnumerator.Current.ToString());
  439. int asciicode = (short)(array[0]);
  440. if (asciicode != 32)
  441. {
  442. a += CEnumerator.Current.ToString();
  443. }
  444. }
  445. string sdate = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Hour.ToString()
  446. + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString();
  447. return a.Split('.')[a.Split('.').Length - 2] + "." + a.Split('.')[a.Split('.').Length - 1];
  448. }
  449. /// <summary>
  450. /// 获取已上传文件大小
  451. /// </summary>
  452. /// <param name="filename">文件名称</param>
  453. /// <param name="path">服务器文件路径</param>
  454. /// <returns></returns>
  455. public static long GetFileSize(string filename, string remoteFilepath)
  456. {
  457. long filesize = 0;
  458. try
  459. {
  460. FtpWebRequest reqFTP;
  461. FileInfo fi = new FileInfo(filename);
  462. string uri;
  463. if (remoteFilepath.Length == 0)
  464. {
  465. uri = "ftp://" + FtpServerIP + "/" + fi.Name;
  466. }
  467. else
  468. {
  469. uri = "ftp://" + FtpServerIP + "/" + remoteFilepath + "/" + fi.Name;
  470. }
  471. reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
  472. reqFTP.KeepAlive = false;
  473. reqFTP.UseBinary = true;
  474. reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);//用户,密码
  475. reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
  476. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  477. filesize = response.ContentLength;
  478. return filesize;
  479. }
  480. catch
  481. {
  482. return 0;
  483. }
  484. }
  485. //public void Connect(String path, string ftpUserID, string ftpPassword)//连接ftp
  486. //{
  487. // // 根据uri创建FtpWebRequest对象
  488. // reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
  489. // // 指定数据传输类型
  490. // reqFTP.UseBinary = true;
  491. // // ftp用户名和密码
  492. // reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  493. //}
  494. #endregion
  495. #region 获取当前目录下明细
  496. /// <summary>
  497. /// 获取当前目录下明细(包含文件和文件夹)
  498. /// </summary>
  499. /// <returns></returns>
  500. public static string[] GetFilesDetailList()
  501. {
  502. string[] downloadFiles;
  503. try
  504. {
  505. StringBuilder result = new StringBuilder();
  506. FtpWebRequest ftp;
  507. ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
  508. ftp.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
  509. ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
  510. WebResponse response = ftp.GetResponse();
  511. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
  512. string line = reader.ReadLine();
  513. while (line != null)
  514. {
  515. result.Append(line);
  516. result.Append("\n");
  517. line = reader.ReadLine();
  518. }
  519. result.Remove(result.ToString().LastIndexOf("\n"), 1);
  520. reader.Close();
  521. response.Close();
  522. return result.ToString().Split('\n');
  523. }
  524. catch (Exception ex)
  525. {
  526. downloadFiles = null;
  527. throw ex;
  528. }
  529. }
  530. /// <summary>
  531. /// 获取当前目录下文件列表(仅文件)
  532. /// </summary>
  533. /// <returns></returns>
  534. public static string[] GetFileList(string mask)
  535. {
  536. string[] downloadFiles;
  537. StringBuilder result = new StringBuilder();
  538. FtpWebRequest reqFTP;
  539. try
  540. {
  541. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
  542. reqFTP.UseBinary = true;
  543. reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
  544. reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
  545. WebResponse response = reqFTP.GetResponse();
  546. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
  547. string line = reader.ReadLine();
  548. while (line != null)
  549. {
  550. if (mask.Trim() != string.Empty && mask.Trim() != "*.*")
  551. {
  552. string mask_ = mask.Substring(0, mask.IndexOf("*"));
  553. if (line.Substring(0, mask_.Length) == mask_)
  554. {
  555. result.Append(line);
  556. result.Append("\n");
  557. }
  558. }
  559. else
  560. {
  561. result.Append(line);
  562. result.Append("\n");
  563. }
  564. line = reader.ReadLine();
  565. }
  566. result.Remove(result.ToString().LastIndexOf('\n'), 1);
  567. reader.Close();
  568. response.Close();
  569. return result.ToString().Split('\n');
  570. }
  571. catch (Exception ex)
  572. {
  573. downloadFiles = null;
  574. throw ex;
  575. }
  576. }
  577. /// <summary>
  578. /// 获取当前目录下所有的文件夹列表(仅文件夹)
  579. /// </summary>
  580. /// <returns></returns>
  581. public static string[] GetDirectoryList()
  582. {
  583. string[] drectory = GetFilesDetailList();
  584. string m = string.Empty;
  585. foreach (string str in drectory)
  586. {
  587. int dirPos = str.IndexOf("<DIR>");
  588. if (dirPos > 0)
  589. {
  590. /*判断 Windows 风格*/
  591. m += str.Substring(dirPos + 5).Trim() + "\n";
  592. }
  593. else if (str.Trim().Substring(0, 1).ToUpper() == "D")
  594. {
  595. /*判断 Unix 风格*/
  596. string dir = str.Substring(54).Trim();
  597. if (dir != "." && dir != "..")
  598. {
  599. m += dir + "\n";
  600. }
  601. }
  602. }
  603. char[] n = new char[] { '\n' };
  604. return m.Split(n);
  605. }
  606. #endregion
  607. #region 删除文件及文件夹
  608. /// <summary>
  609. /// 删除文件
  610. /// </summary>
  611. /// <param name="fileName"></param>
  612. public static bool Delete(string fileName)
  613. {
  614. try
  615. {
  616. string uri = ftpURI + fileName;
  617. FtpWebRequest reqFTP;
  618. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
  619. reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
  620. reqFTP.KeepAlive = false;
  621. reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
  622. string result = String.Empty;
  623. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  624. long size = response.ContentLength;
  625. Stream datastream = response.GetResponseStream();
  626. StreamReader sr = new StreamReader(datastream);
  627. result = sr.ReadToEnd();
  628. sr.Close();
  629. datastream.Close();
  630. response.Close();
  631. return true;
  632. }
  633. catch (Exception ex)
  634. {
  635. return false;
  636. throw ex;
  637. }
  638. }
  639. /// <summary>
  640. /// 删除文件夹
  641. /// </summary>
  642. /// <param name="folderName"></param>
  643. public static void RemoveDirectory(string folderName)
  644. {
  645. try
  646. {
  647. string uri = ftpURI + folderName;
  648. FtpWebRequest reqFTP;
  649. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
  650. reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
  651. reqFTP.KeepAlive = false;
  652. reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
  653. string result = String.Empty;
  654. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  655. long size = response.ContentLength;
  656. Stream datastream = response.GetResponseStream();
  657. StreamReader sr = new StreamReader(datastream);
  658. result = sr.ReadToEnd();
  659. sr.Close();
  660. datastream.Close();
  661. response.Close();
  662. }
  663. catch (Exception ex)
  664. {
  665. throw ex;
  666. }
  667. }
  668. #endregion
  669. #region 其他操作
  670. /// <summary>
  671. /// 获取指定文件大小
  672. /// </summary>
  673. /// <param name="filename"></param>
  674. /// <returns></returns>
  675. public static long GetFileSize(string filename)
  676. {
  677. FtpWebRequest reqFTP;
  678. long fileSize = 0;
  679. try
  680. {
  681. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
  682. reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
  683. reqFTP.UseBinary = true;
  684. reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
  685. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  686. Stream ftpStream = response.GetResponseStream();
  687. fileSize = response.ContentLength;
  688. ftpStream.Close();
  689. response.Close();
  690. }
  691. catch (Exception ex)
  692. {
  693. throw ex;
  694. }
  695. return fileSize;
  696. }
  697. /// <summary>
  698. /// 判断当前目录下指定的子目录是否存在
  699. /// </summary>
  700. /// <param name="RemoteDirectoryName">指定的目录名</param>
  701. public bool DirectoryExist(string RemoteDirectoryName)
  702. {
  703. try
  704. {
  705. string[] dirList = GetDirectoryList();
  706. foreach (string str in dirList)
  707. {
  708. if (str.Trim() == RemoteDirectoryName.Trim())
  709. {
  710. return true;
  711. }
  712. }
  713. return false;
  714. }
  715. catch
  716. {
  717. return false;
  718. }
  719. }
  720. /// <summary>
  721. /// 判断当前目录下指定的文件是否存在
  722. /// </summary>
  723. /// <param name="RemoteFileName">远程文件名</param>
  724. public bool FileExist(string RemoteFileName)
  725. {
  726. string[] fileList = GetFileList("*.*");
  727. foreach (string str in fileList)
  728. {
  729. if (str.Trim() == RemoteFileName.Trim())
  730. {
  731. return true;
  732. }
  733. }
  734. return false;
  735. }
  736. /// <summary>
  737. /// 创建文件夹
  738. /// </summary>
  739. /// <param name="dirName"></param>
  740. public void MakeDir(string dirName)
  741. {
  742. FtpWebRequest reqFTP;
  743. try
  744. {
  745. // dirName = name of the directory to create.
  746. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
  747. reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
  748. reqFTP.UseBinary = true;
  749. reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
  750. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  751. Stream ftpStream = response.GetResponseStream();
  752. ftpStream.Close();
  753. response.Close();
  754. }
  755. catch (Exception ex)
  756. {
  757. throw ex;
  758. }
  759. }
  760. /// <summary>
  761. /// 改名
  762. /// </summary>
  763. /// <param name="currentFilename"></param>
  764. /// <param name="newFilename"></param>
  765. public void ReName(string currentFilename, string newFilename)
  766. {
  767. FtpWebRequest reqFTP;
  768. try
  769. {
  770. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename));
  771. reqFTP.Method = WebRequestMethods.Ftp.Rename;
  772. reqFTP.RenameTo = newFilename;
  773. reqFTP.UseBinary = true;
  774. reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
  775. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  776. Stream ftpStream = response.GetResponseStream();
  777. ftpStream.Close();
  778. response.Close();
  779. }
  780. catch (Exception ex)
  781. {
  782. throw ex;
  783. }
  784. }
  785. /// <summary>
  786. /// 移动文件
  787. /// </summary>
  788. /// <param name="currentFilename"></param>
  789. /// <param name="newFilename"></param>
  790. public void MovieFile(string currentFilename, string newDirectory)
  791. {
  792. ReName(currentFilename, newDirectory);
  793. }
  794. /// <summary>
  795. /// 切换当前目录
  796. /// </summary>
  797. /// <param name="DirectoryName"></param>
  798. /// <param name="IsRoot">true 绝对路径 false 相对路径</param>
  799. public void GotoDirectory(string DirectoryName, bool IsRoot)
  800. {
  801. if (IsRoot)
  802. {
  803. ftpRemotePath = DirectoryName;
  804. }
  805. else
  806. {
  807. ftpRemotePath += DirectoryName + "/";
  808. }
  809. ftpURI = "ftp://" + FtpServerIP + "/" + ftpRemotePath + "/";
  810. }
  811. #endregion
  812. }
  813. }
复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持程序员之家。

您可能感兴趣的文章:

  • C#版ftp方法实现类的代码
  • c#操作ftp类分享
  • C#实现自定义FTP操作封装类实例
  • 分享用于操作FTP的客户端C#类
  • C#操作ftp类完整实例


回复

使用道具 举报