1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Net;
  5. using System.IO;
  6. using System.Globalization;
  7. using System.Text.RegularExpressions;
  8.  
  9. namespace System.Net.Ftp
  10. {
  11. /// <summary>
  12. /// FTP处理操作类
  13. /// 功能:
  14. /// 下载文件
  15. /// 上传文件
  16. /// 上传文件的进度信息
  17. /// 下载文件的进度信息
  18. /// 删除文件
  19. /// 列出文件
  20. /// 列出目录
  21. /// 进入子目录
  22. /// 退出当前目录返回上一层目录
  23. /// 判断远程文件是否存在
  24. /// 判断远程文件是否存在
  25. /// 删除远程文件
  26. /// 建立目录
  27. /// 删除目录
  28. /// 文件(目录)改名
  29.  
  30. /// </summary>
  31. /// <remarks>
  32. /// 创建人:南疯
  33. /// 创建时间:2007年4月28日
  34. /// </remarks>
  35. #region 文件信息结构
  36. public struct FileStruct
  37. {
  38. public string Flags;
  39. public string Owner;
  40. public string Group;
  41. public bool IsDirectory;
  42. public DateTime CreateTime;
  43. public string Name;
  44. }
  45. public enum FileListStyle
  46. {
  47. UnixStyle,
  48. WindowsStyle,
  49. Unknown
  50. }
  51. #endregion
  52. public class clsFTP
  53. {
  54. #region 属性信息
  55. /// <summary>
  56. /// FTP请求对象
  57. /// </summary>
  58. FtpWebRequest Request = null;
  59. /// <summary>
  60. /// FTP响应对象
  61. /// </summary>
  62. FtpWebResponse Response = null;
  63. /// <summary>
  64. /// FTP服务器地址
  65. /// </summary>
  66. private Uri _Uri;
  67. /// <summary>
  68. /// FTP服务器地址
  69. /// </summary>
  70. public Uri Uri
  71. {
  72. get
  73. {
  74. if (_DirectoryPath == "/")
  75. {
  76. return _Uri;
  77. }
  78. else
  79. {
  80. string strUri = _Uri.ToString();
  81. if (strUri.EndsWith("/"))
  82. {
  83. strUri = strUri.Substring(, strUri.Length - );
  84. }
  85. return new Uri(strUri + this.DirectoryPath);
  86. }
  87. }
  88. set
  89. {
  90. if (value.Scheme != Uri.UriSchemeFtp)
  91. {
  92. throw new Exception("Ftp 地址格式错误!");
  93. }
  94. _Uri = new Uri(value.GetLeftPart(UriPartial.Authority));
  95. _DirectoryPath = value.AbsolutePath;
  96. if (!_DirectoryPath.EndsWith("/"))
  97. {
  98. _DirectoryPath += "/";
  99. }
  100. }
  101. }
  102.  
  103. /// <summary>
  104. /// 当前工作目录
  105. /// </summary>
  106. private string _DirectoryPath;
  107.  
  108. /// <summary>
  109. /// 当前工作目录
  110. /// </summary>
  111. public string DirectoryPath
  112. {
  113. get { return _DirectoryPath; }
  114. set { _DirectoryPath = value; }
  115. }
  116.  
  117. /// <summary>
  118. /// FTP登录用户
  119. /// </summary>
  120. private string _UserName;
  121. /// <summary>
  122. /// FTP登录用户
  123. /// </summary>
  124. public string UserName
  125. {
  126. get { return _UserName; }
  127. set { _UserName = value; }
  128. }
  129.  
  130. /// <summary>
  131. /// 错误信息
  132. /// </summary>
  133. private string _ErrorMsg;
  134. /// <summary>
  135. /// 错误信息
  136. /// </summary>
  137. public string ErrorMsg
  138. {
  139. get { return _ErrorMsg; }
  140. set { _ErrorMsg = value; }
  141. }
  142.  
  143. /// <summary>
  144. /// FTP登录密码
  145. /// </summary>
  146. private string _Password;
  147. /// <summary>
  148. /// FTP登录密码
  149. /// </summary>
  150. public string Password
  151. {
  152. get { return _Password; }
  153. set { _Password = value; }
  154. }
  155.  
  156. /// <summary>
  157. /// 连接FTP服务器的代理服务
  158. /// </summary>
  159. private WebProxy _Proxy = null;
  160. /// <summary>
  161. /// 连接FTP服务器的代理服务
  162. /// </summary>
  163. public WebProxy Proxy
  164. {
  165. get
  166. {
  167. return _Proxy;
  168. }
  169. set
  170. {
  171. _Proxy = value;
  172. }
  173. }
  174.  
  175. /// <summary>
  176. /// 是否需要删除临时文件
  177. /// </summary>
  178. private bool _isDeleteTempFile = false;
  179. /// <summary>
  180. /// 异步上传所临时生成的文件
  181. /// </summary>
  182. private string _UploadTempFile = "";
  183. #endregion
  184. #region 事件
  185. public delegate void De_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e);
  186. public delegate void De_DownloadDataCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
  187. public delegate void De_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e);
  188. public delegate void De_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e);
  189.  
  190. /// <summary>
  191. /// 异步下载进度发生改变触发的事件
  192. /// </summary>
  193. public event De_DownloadProgressChanged DownloadProgressChanged;
  194. /// <summary>
  195. /// 异步下载文件完成之后触发的事件
  196. /// </summary>
  197. public event De_DownloadDataCompleted DownloadDataCompleted;
  198. /// <summary>
  199. /// 异步上传进度发生改变触发的事件
  200. /// </summary>
  201. public event De_UploadProgressChanged UploadProgressChanged;
  202. /// <summary>
  203. /// 异步上传文件完成之后触发的事件
  204. /// </summary>
  205. public event De_UploadFileCompleted UploadFileCompleted;
  206. #endregion
  207. #region 构造析构函数
  208. /// <summary>
  209. /// 构造函数
  210. /// </summary>
  211. /// <param name="FtpUri">FTP地址</param>
  212. /// <param name="strUserName">登录用户名</param>
  213. /// <param name="strPassword">登录密码</param>
  214. public clsFTP(Uri FtpUri, string strUserName, string strPassword)
  215. {
  216. this._Uri = new Uri(FtpUri.GetLeftPart(UriPartial.Authority));
  217. _DirectoryPath = FtpUri.AbsolutePath;
  218. if (!_DirectoryPath.EndsWith("/"))
  219. {
  220. _DirectoryPath += "/";
  221. }
  222. this._UserName = strUserName;
  223. this._Password = strPassword;
  224. this._Proxy = null;
  225. }
  226. /// <summary>
  227. /// 构造函数
  228. /// </summary>
  229. /// <param name="FtpUri">FTP地址</param>
  230. /// <param name="strUserName">登录用户名</param>
  231. /// <param name="strPassword">登录密码</param>
  232. /// <param name="objProxy">连接代理</param>
  233. public clsFTP(Uri FtpUri, string strUserName, string strPassword, WebProxy objProxy)
  234. {
  235. this._Uri = new Uri(FtpUri.GetLeftPart(UriPartial.Authority));
  236. _DirectoryPath = FtpUri.AbsolutePath;
  237. if (!_DirectoryPath.EndsWith("/"))
  238. {
  239. _DirectoryPath += "/";
  240. }
  241. this._UserName = strUserName;
  242. this._Password = strPassword;
  243. this._Proxy = objProxy;
  244. }
  245. /// <summary>
  246. /// 构造函数
  247. /// </summary>
  248. public clsFTP()
  249. {
  250. this._UserName = "anonymous"; //匿名用户
  251. this._Password = "@anonymous";
  252. this._Uri = null;
  253. this._Proxy = null;
  254. }
  255.  
  256. /// <summary>
  257. /// 析构函数
  258. /// </summary>
  259. ~clsFTP()
  260. {
  261. if (Response != null)
  262. {
  263. Response.Close();
  264. Response = null;
  265. }
  266. if (Request != null)
  267. {
  268. Request.Abort();
  269. Request = null;
  270. }
  271. }
  272. #endregion
  273. #region 建立连接
  274. /// <summary>
  275. /// 建立FTP链接,返回响应对象
  276. /// </summary>
  277. /// <param name="uri">FTP地址</param>
  278. /// <param name="FtpMathod">操作命令</param>
  279. private FtpWebResponse Open(Uri uri, string FtpMathod)
  280. {
  281. try
  282. {
  283. Request = (FtpWebRequest) WebRequest.Create(uri);
  284. Request.Method = FtpMathod;
  285. Request.UseBinary = true;
  286. Request.Credentials = new NetworkCredential(this.UserName, this.Password);
  287. if (this.Proxy != null)
  288. {
  289. Request.Proxy = this.Proxy;
  290. }
  291. return (FtpWebResponse) Request.GetResponse();
  292. }
  293. catch (Exception ep)
  294. {
  295. ErrorMsg = ep.ToString();
  296. throw ep;
  297. }
  298. }
  299. /// <summary>
  300. /// 建立FTP链接,返回请求对象
  301. /// </summary>
  302. /// <param name="uri">FTP地址</param>
  303. /// <param name="FtpMathod">操作命令</param>
  304. private FtpWebRequest OpenRequest(Uri uri, string FtpMathod)
  305. {
  306. try
  307. {
  308. Request = (FtpWebRequest) WebRequest.Create(uri);
  309. Request.Method = FtpMathod;
  310. Request.UseBinary = true;
  311. Request.Credentials = new NetworkCredential(this.UserName, this.Password);
  312. if (this.Proxy != null)
  313. {
  314. Request.Proxy = this.Proxy;
  315. }
  316. return Request;
  317. }
  318. catch (Exception ep)
  319. {
  320. ErrorMsg = ep.ToString();
  321. throw ep;
  322. }
  323. }
  324. #endregion
  325. #region 下载文件
  326.  
  327. /// <summary>
  328. /// 从FTP服务器下载文件,使用与远程文件同名的文件名来保存文件
  329. /// </summary>
  330. /// <param name="RemoteFileName">远程文件名</param>
  331. /// <param name="LocalPath">本地路径</param>
  332.  
  333. public bool DownloadFile(string RemoteFileName, string LocalPath)
  334. {
  335. return DownloadFile(RemoteFileName, LocalPath, RemoteFileName);
  336. }
  337. /// <summary>
  338. /// 从FTP服务器下载文件,指定本地路径和本地文件名
  339. /// </summary>
  340. /// <param name="RemoteFileName">远程文件名</param>
  341. /// <param name="LocalPath">本地路径</param>
  342. /// <param name="LocalFilePath">保存文件的本地路径,后面带有"\"</param>
  343. /// <param name="LocalFileName">保存本地的文件名</param>
  344. public bool DownloadFile(string RemoteFileName, string LocalPath, string LocalFileName)
  345. {
  346. byte[] bt = null;
  347. try
  348. {
  349. if (!IsValidFileChars(RemoteFileName) || !IsValidFileChars(LocalFileName) || !IsValidPathChars(LocalPath))
  350. {
  351. throw new Exception("非法文件名或目录名!");
  352. }
  353. if (!Directory.Exists(LocalPath))
  354. {
  355. throw new Exception("本地文件路径不存在!");
  356. }
  357.  
  358. string LocalFullPath = Path.Combine(LocalPath, LocalFileName);
  359. if (File.Exists(LocalFullPath))
  360. {
  361. throw new Exception("当前路径下已经存在同名文件!");
  362. }
  363. bt = DownloadFile(RemoteFileName);
  364. if (bt != null)
  365. {
  366. FileStream stream = new FileStream(LocalFullPath, FileMode.Create);
  367. stream.Write(bt, , bt.Length);
  368. stream.Flush();
  369. stream.Close();
  370. return true;
  371. }
  372. else
  373. {
  374. return false;
  375. }
  376. }
  377. catch (Exception ep)
  378. {
  379. ErrorMsg = ep.ToString();
  380. throw ep;
  381. }
  382. }
  383.  
  384. /// <summary>
  385. /// 从FTP服务器下载文件,返回文件二进制数据
  386. /// </summary>
  387. /// <param name="RemoteFileName">远程文件名</param>
  388. public byte[] DownloadFile(string RemoteFileName)
  389. {
  390. try
  391. {
  392. if (!IsValidFileChars(RemoteFileName))
  393. {
  394. throw new Exception("非法文件名或目录名!");
  395. }
  396. Response = Open(new Uri(this.Uri.ToString() + RemoteFileName), WebRequestMethods.Ftp.DownloadFile);
  397. Stream Reader = Response.GetResponseStream();
  398.  
  399. MemoryStream mem = new MemoryStream( * );
  400. byte[] buffer = new byte[];
  401. int bytesRead = ;
  402. int TotalByteRead = ;
  403. while (true)
  404. {
  405. bytesRead = Reader.Read(buffer, , buffer.Length);
  406. TotalByteRead += bytesRead;
  407. if (bytesRead == )
  408. break;
  409. mem.Write(buffer, , bytesRead);
  410. }
  411. if (mem.Length > )
  412. {
  413. return mem.ToArray();
  414. }
  415. else
  416. {
  417. return null;
  418. }
  419. }
  420. catch (Exception ep)
  421. {
  422. ErrorMsg = ep.ToString();
  423. throw ep;
  424. }
  425. }
  426. #endregion
  427. #region 异步下载文件
  428. /// <summary>
  429. /// 从FTP服务器异步下载文件,指定本地路径和本地文件名
  430. /// </summary>
  431. /// <param name="RemoteFileName">远程文件名</param>
  432. /// <param name="LocalPath">保存文件的本地路径,后面带有"\"</param>
  433. /// <param name="LocalFileName">保存本地的文件名</param>
  434. public void DownloadFileAsync(string RemoteFileName, string LocalPath, string LocalFileName)
  435. {
  436. byte[] bt = null;
  437. try
  438. {
  439. if (!IsValidFileChars(RemoteFileName) || !IsValidFileChars(LocalFileName) || !IsValidPathChars(LocalPath))
  440. {
  441. throw new Exception("非法文件名或目录名!");
  442. }
  443. if (!Directory.Exists(LocalPath))
  444. {
  445. throw new Exception("本地文件路径不存在!");
  446. }
  447.  
  448. string LocalFullPath = Path.Combine(LocalPath, LocalFileName);
  449. if (File.Exists(LocalFullPath))
  450. {
  451. throw new Exception("当前路径下已经存在同名文件!");
  452. }
  453. DownloadFileAsync(RemoteFileName, LocalFullPath);
  454.  
  455. }
  456. catch (Exception ep)
  457. {
  458. ErrorMsg = ep.ToString();
  459. throw ep;
  460. }
  461. }
  462.  
  463. /// <summary>
  464. /// 从FTP服务器异步下载文件,指定本地完整路径文件名
  465. /// </summary>
  466. /// <param name="RemoteFileName">远程文件名</param>
  467. /// <param name="LocalFullPath">本地完整路径文件名</param>
  468. public void DownloadFileAsync(string RemoteFileName, string LocalFullPath)
  469. {
  470. try
  471. {
  472. if (!IsValidFileChars(RemoteFileName))
  473. {
  474. throw new Exception("非法文件名或目录名!");
  475. }
  476. if (File.Exists(LocalFullPath))
  477. {
  478. throw new Exception("当前路径下已经存在同名文件!");
  479. }
  480. MyWebClient client = new MyWebClient();
  481.  
  482. client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
  483. client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted);
  484. client.Credentials = new NetworkCredential(this.UserName, this.Password);
  485. if (this.Proxy != null)
  486. {
  487. client.Proxy = this.Proxy;
  488. }
  489. client.DownloadFileAsync(new Uri(this.Uri.ToString() + RemoteFileName), LocalFullPath);
  490. }
  491. catch (Exception ep)
  492. {
  493. ErrorMsg = ep.ToString();
  494. throw ep;
  495. }
  496. }
  497.  
  498. /// <summary>
  499. /// 异步下载文件完成之后触发的事件
  500. /// </summary>
  501. /// <param name="sender">下载对象</param>
  502. /// <param name="e">数据信息对象</param>
  503. void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
  504. {
  505. if (DownloadDataCompleted != null)
  506. {
  507. DownloadDataCompleted(sender, e);
  508. }
  509. }
  510.  
  511. /// <summary>
  512. /// 异步下载进度发生改变触发的事件
  513. /// </summary>
  514. /// <param name="sender">下载对象</param>
  515. /// <param name="e">进度信息对象</param>
  516. void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
  517. {
  518. if (DownloadProgressChanged != null)
  519. {
  520. DownloadProgressChanged(sender, e);
  521. }
  522. }
  523. #endregion
  524. #region 上传文件
  525. /// <summary>
  526. /// 上传文件到FTP服务器
  527. /// </summary>
  528. /// <param name="LocalFullPath">本地带有完整路径的文件名</param>
  529. public bool UploadFile(string LocalFullPath)
  530. {
  531. return UploadFile(LocalFullPath, Path.GetFileName(LocalFullPath), false);
  532. }
  533. /// <summary>
  534. /// 上传文件到FTP服务器
  535. /// </summary>
  536. /// <param name="LocalFullPath">本地带有完整路径的文件</param>
  537. /// <param name="OverWriteRemoteFile">是否覆盖远程服务器上面同名的文件</param>
  538. public bool UploadFile(string LocalFullPath, bool OverWriteRemoteFile)
  539. {
  540. return UploadFile(LocalFullPath, Path.GetFileName(LocalFullPath), OverWriteRemoteFile);
  541. }
  542. /// <summary>
  543. /// 上传文件到FTP服务器
  544. /// </summary>
  545. /// <param name="LocalFullPath">本地带有完整路径的文件</param>
  546. /// <param name="RemoteFileName">要在FTP服务器上面保存文件名</param>
  547. public bool UploadFile(string LocalFullPath, string RemoteFileName)
  548. {
  549. return UploadFile(LocalFullPath, RemoteFileName, false);
  550. }
  551. /// <summary>
  552. /// 上传文件到FTP服务器
  553. /// </summary>
  554. /// <param name="LocalFullPath">本地带有完整路径的文件名</param>
  555. /// <param name="RemoteFileName">要在FTP服务器上面保存文件名</param>
  556. /// <param name="OverWriteRemoteFile">是否覆盖远程服务器上面同名的文件</param>
  557. public bool UploadFile(string LocalFullPath, string RemoteFileName, bool OverWriteRemoteFile)
  558. {
  559. try
  560. {
  561. if (!IsValidFileChars(RemoteFileName) || !IsValidFileChars(Path.GetFileName(LocalFullPath)) || !IsValidPathChars(Path.GetDirectoryName(LocalFullPath)))
  562. {
  563. throw new Exception("非法文件名或目录名!");
  564. }
  565. if (File.Exists(LocalFullPath))
  566. {
  567. FileStream Stream = new FileStream(LocalFullPath, FileMode.Open, FileAccess.Read);
  568. byte[] bt = new byte[Stream.Length];
  569. Stream.Read(bt, , (Int32) Stream.Length); //注意,因为Int32的最大限制,最大上传文件只能是大约2G多一点
  570. Stream.Close();
  571. return UploadFile(bt, RemoteFileName, OverWriteRemoteFile);
  572. }
  573. else
  574. {
  575. throw new Exception("本地文件不存在!");
  576. }
  577. }
  578. catch (Exception ep)
  579. {
  580. ErrorMsg = ep.ToString();
  581. throw ep;
  582. }
  583. }
  584. /// <summary>
  585. /// 上传文件到FTP服务器
  586. /// </summary>
  587. /// <param name="FileBytes">上传的二进制数据</param>
  588. /// <param name="RemoteFileName">要在FTP服务器上面保存文件名</param>
  589. public bool UploadFile(byte[] FileBytes, string RemoteFileName)
  590. {
  591. if (!IsValidFileChars(RemoteFileName))
  592. {
  593. throw new Exception("非法文件名或目录名!");
  594. }
  595. return UploadFile(FileBytes, RemoteFileName, false);
  596. }
  597. /// <summary>
  598. /// 上传文件到FTP服务器
  599. /// </summary>
  600. /// <param name="FileBytes">文件二进制内容</param>
  601. /// <param name="RemoteFileName">要在FTP服务器上面保存文件名</param>
  602. /// <param name="OverWriteRemoteFile">是否覆盖远程服务器上面同名的文件</param>
  603. public bool UploadFile(byte[] FileBytes, string RemoteFileName, bool OverWriteRemoteFile)
  604. {
  605. try
  606. {
  607. if (!IsValidFileChars(RemoteFileName))
  608. {
  609. throw new Exception("非法文件名!");
  610. }
  611. if (!OverWriteRemoteFile && FileExist(RemoteFileName))
  612. {
  613. throw new Exception("FTP服务上面已经存在同名文件!");
  614. }
  615. Response = Open(new Uri(this.Uri.ToString() + RemoteFileName), WebRequestMethods.Ftp.UploadFile);
  616. Stream requestStream = Request.GetRequestStream();
  617. MemoryStream mem = new MemoryStream(FileBytes);
  618.  
  619. byte[] buffer = new byte[];
  620. int bytesRead = ;
  621. int TotalRead = ;
  622. while (true)
  623. {
  624. bytesRead = mem.Read(buffer, , buffer.Length);
  625. if (bytesRead == )
  626. break;
  627. TotalRead += bytesRead;
  628. requestStream.Write(buffer, , bytesRead);
  629. }
  630. requestStream.Close();
  631. Response = (FtpWebResponse) Request.GetResponse();
  632. mem.Close();
  633. mem.Dispose();
  634. FileBytes = null;
  635. return true;
  636. }
  637. catch (Exception ep)
  638. {
  639. ErrorMsg = ep.ToString();
  640. throw ep;
  641. }
  642. }
  643. #endregion
  644. #region 异步上传文件
  645. /// <summary>
  646. /// 异步上传文件到FTP服务器
  647. /// </summary>
  648. /// <param name="LocalFullPath">本地带有完整路径的文件名</param>
  649. public void UploadFileAsync(string LocalFullPath)
  650. {
  651. UploadFileAsync(LocalFullPath, Path.GetFileName(LocalFullPath), false);
  652. }
  653. /// <summary>
  654. /// 异步上传文件到FTP服务器
  655. /// </summary>
  656. /// <param name="LocalFullPath">本地带有完整路径的文件</param>
  657. /// <param name="OverWriteRemoteFile">是否覆盖远程服务器上面同名的文件</param>
  658. public void UploadFileAsync(string LocalFullPath, bool OverWriteRemoteFile)
  659. {
  660. UploadFileAsync(LocalFullPath, Path.GetFileName(LocalFullPath), OverWriteRemoteFile);
  661. }
  662. /// <summary>
  663. /// 异步上传文件到FTP服务器
  664. /// </summary>
  665. /// <param name="LocalFullPath">本地带有完整路径的文件</param>
  666. /// <param name="RemoteFileName">要在FTP服务器上面保存文件名</param>
  667. public void UploadFileAsync(string LocalFullPath, string RemoteFileName)
  668. {
  669. UploadFileAsync(LocalFullPath, RemoteFileName, false);
  670. }
  671. /// <summary>
  672. /// 异步上传文件到FTP服务器
  673. /// </summary>
  674. /// <param name="LocalFullPath">本地带有完整路径的文件名</param>
  675. /// <param name="RemoteFileName">要在FTP服务器上面保存文件名</param>
  676. /// <param name="OverWriteRemoteFile">是否覆盖远程服务器上面同名的文件</param>
  677. public void UploadFileAsync(string LocalFullPath, string RemoteFileName, bool OverWriteRemoteFile)
  678. {
  679. try
  680. {
  681. if (!IsValidFileChars(RemoteFileName) || !IsValidFileChars(Path.GetFileName(LocalFullPath)) || !IsValidPathChars(Path.GetDirectoryName(LocalFullPath)))
  682. {
  683. throw new Exception("非法文件名或目录名!");
  684. }
  685. if (!OverWriteRemoteFile && FileExist(RemoteFileName))
  686. {
  687. throw new Exception("FTP服务上面已经存在同名文件!");
  688. }
  689. if (File.Exists(LocalFullPath))
  690. {
  691. MyWebClient client = new MyWebClient();
  692.  
  693. client.UploadProgressChanged += new UploadProgressChangedEventHandler(client_UploadProgressChanged);
  694. client.UploadFileCompleted += new UploadFileCompletedEventHandler(client_UploadFileCompleted);
  695. client.Credentials = new NetworkCredential(this.UserName, this.Password);
  696. if (this.Proxy != null)
  697. {
  698. client.Proxy = this.Proxy;
  699. }
  700. client.UploadFileAsync(new Uri(this.Uri.ToString() + RemoteFileName), LocalFullPath);
  701.  
  702. }
  703. else
  704. {
  705. throw new Exception("本地文件不存在!");
  706. }
  707. }
  708. catch (Exception ep)
  709. {
  710. ErrorMsg = ep.ToString();
  711. throw ep;
  712. }
  713. }
  714. /// <summary>
  715. /// 异步上传文件到FTP服务器
  716. /// </summary>
  717. /// <param name="FileBytes">上传的二进制数据</param>
  718. /// <param name="RemoteFileName">要在FTP服务器上面保存文件名</param>
  719. public void UploadFileAsync(byte[] FileBytes, string RemoteFileName)
  720. {
  721. if (!IsValidFileChars(RemoteFileName))
  722. {
  723. throw new Exception("非法文件名或目录名!");
  724. }
  725. UploadFileAsync(FileBytes, RemoteFileName, false);
  726. }
  727. /// <summary>
  728. /// 异步上传文件到FTP服务器
  729. /// </summary>
  730. /// <param name="FileBytes">文件二进制内容</param>
  731. /// <param name="RemoteFileName">要在FTP服务器上面保存文件名</param>
  732. /// <param name="OverWriteRemoteFile">是否覆盖远程服务器上面同名的文件</param>
  733. public void UploadFileAsync(byte[] FileBytes, string RemoteFileName, bool OverWriteRemoteFile)
  734. {
  735. try
  736. {
  737.  
  738. if (!IsValidFileChars(RemoteFileName))
  739. {
  740. throw new Exception("非法文件名!");
  741. }
  742. if (!OverWriteRemoteFile && FileExist(RemoteFileName))
  743. {
  744. throw new Exception("FTP服务上面已经存在同名文件!");
  745. }
  746. string TempPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Templates);
  747. if (!TempPath.EndsWith("\\"))
  748. {
  749. TempPath += "\\";
  750. }
  751. string TempFile = TempPath + Path.GetRandomFileName();
  752. TempFile = Path.ChangeExtension(TempFile, Path.GetExtension(RemoteFileName));
  753. FileStream Stream = new FileStream(TempFile, FileMode.CreateNew, FileAccess.Write);
  754. Stream.Write(FileBytes, , FileBytes.Length); //注意,因为Int32的最大限制,最大上传文件只能是大约2G多一点
  755. Stream.Flush();
  756. Stream.Close();
  757. Stream.Dispose();
  758. _isDeleteTempFile = true;
  759. _UploadTempFile = TempFile;
  760. FileBytes = null;
  761. UploadFileAsync(TempFile, RemoteFileName, OverWriteRemoteFile);
  762.  
  763. }
  764. catch (Exception ep)
  765. {
  766. ErrorMsg = ep.ToString();
  767. throw ep;
  768. }
  769. }
  770.  
  771. /// <summary>
  772. /// 异步上传文件完成之后触发的事件
  773. /// </summary>
  774. /// <param name="sender">下载对象</param>
  775. /// <param name="e">数据信息对象</param>
  776. void client_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
  777. {
  778. if (_isDeleteTempFile)
  779. {
  780. if (File.Exists(_UploadTempFile))
  781. {
  782. File.SetAttributes(_UploadTempFile, FileAttributes.Normal);
  783. File.Delete(_UploadTempFile);
  784. }
  785. _isDeleteTempFile = false;
  786. }
  787. if (UploadFileCompleted != null)
  788. {
  789. UploadFileCompleted(sender, e);
  790. }
  791. }
  792.  
  793. /// <summary>
  794. /// 异步上传进度发生改变触发的事件
  795. /// </summary>
  796. /// <param name="sender">下载对象</param>
  797. /// <param name="e">进度信息对象</param>
  798. void client_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
  799. {
  800. if (UploadProgressChanged != null)
  801. {
  802. UploadProgressChanged(sender, e);
  803. }
  804. }
  805. #endregion
  806. #region 列出目录文件信息
  807. /// <summary>
  808. /// 列出FTP服务器上面当前目录的所有文件和目录
  809. /// </summary>
  810. public FileStruct[] ListFilesAndDirectories()
  811. {
  812. Response = Open(this.Uri, WebRequestMethods.Ftp.ListDirectoryDetails);
  813. StreamReader stream = new StreamReader(Response.GetResponseStream(), Encoding.Default);
  814. string Datastring = stream.ReadToEnd();
  815. FileStruct[] list = GetList(Datastring);
  816. return list;
  817. }
  818. /// <summary>
  819. /// 列出FTP服务器上面当前目录的所有文件
  820. /// </summary>
  821. public FileStruct[] ListFiles()
  822. {
  823. FileStruct[] listAll = ListFilesAndDirectories();
  824. List<FileStruct> listFile = new List<FileStruct>();
  825. foreach (FileStruct file in listAll)
  826. {
  827. if (!file.IsDirectory)
  828. {
  829. listFile.Add(file);
  830. }
  831. }
  832. return listFile.ToArray();
  833. }
  834.  
  835. /// <summary>
  836. /// 列出FTP服务器上面当前目录的所有的目录
  837. /// </summary>
  838. public FileStruct[] ListDirectories()
  839. {
  840. FileStruct[] listAll = ListFilesAndDirectories();
  841. List<FileStruct> listDirectory = new List<FileStruct>();
  842. foreach (FileStruct file in listAll)
  843. {
  844. if (file.IsDirectory)
  845. {
  846. listDirectory.Add(file);
  847. }
  848. }
  849. return listDirectory.ToArray();
  850. }
  851. /// <summary>
  852. /// 获得文件和目录列表
  853. /// </summary>
  854. /// <param name="datastring">FTP返回的列表字符信息</param>
  855. private FileStruct[] GetList(string datastring)
  856. {
  857. List<FileStruct> myListArray = new List<FileStruct>();
  858. string[] dataRecords = datastring.Split('\n');
  859. FileListStyle _directoryListStyle = GuessFileListStyle(dataRecords);
  860. foreach (string s in dataRecords)
  861. {
  862. if (_directoryListStyle != FileListStyle.Unknown && s != "")
  863. {
  864. FileStruct f = new FileStruct();
  865. f.Name = "..";
  866. switch (_directoryListStyle)
  867. {
  868. case FileListStyle.UnixStyle:
  869. f = ParseFileStructFromUnixStyleRecord(s);
  870. break;
  871. case FileListStyle.WindowsStyle:
  872. f = ParseFileStructFromWindowsStyleRecord(s);
  873. break;
  874. }
  875. if (!(f.Name == "." || f.Name == ".."))
  876. {
  877. myListArray.Add(f);
  878. }
  879. }
  880. }
  881. return myListArray.ToArray();
  882. }
  883.  
  884. /// <summary>
  885. /// 从Windows格式中返回文件信息
  886. /// </summary>
  887. /// <param name="Record">文件信息</param>
  888. private FileStruct ParseFileStructFromWindowsStyleRecord(string Record)
  889. {
  890. FileStruct f = new FileStruct();
  891. string processstr = Record.Trim();
  892. string dateStr = processstr.Substring(, );
  893. processstr = (processstr.Substring(, processstr.Length - )).Trim();
  894. string timeStr = processstr.Substring(, );
  895. processstr = (processstr.Substring(, processstr.Length - )).Trim();
  896. DateTimeFormatInfo myDTFI = new CultureInfo("en-US", false).DateTimeFormat;
  897. myDTFI.ShortTimePattern = "t";
  898. f.CreateTime = DateTime.Parse(dateStr + " " + timeStr, myDTFI);
  899. if (processstr.Substring(, ) == "<DIR>")
  900. {
  901. f.IsDirectory = true;
  902. processstr = (processstr.Substring(, processstr.Length - )).Trim();
  903. }
  904. else
  905. {
  906. string[] strs = processstr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); // true);
  907. processstr = strs[];
  908. f.IsDirectory = false;
  909. }
  910. f.Name = processstr;
  911. return f;
  912. }
  913.  
  914. /// <summary>
  915. /// 判断文件列表的方式Window方式还是Unix方式
  916. /// </summary>
  917. /// <param name="recordList">文件信息列表</param>
  918. private FileListStyle GuessFileListStyle(string[] recordList)
  919. {
  920. foreach (string s in recordList)
  921. {
  922. if (s.Length >
  923. && Regex.IsMatch(s.Substring(, ), "(-|d)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)"))
  924. {
  925. return FileListStyle.UnixStyle;
  926. }
  927. else if (s.Length >
  928. && Regex.IsMatch(s.Substring(, ), "[0-9][0-9]-[0-9][0-9]-[0-9][0-9]"))
  929. {
  930. return FileListStyle.WindowsStyle;
  931. }
  932. }
  933. return FileListStyle.Unknown;
  934. }
  935.  
  936. /// <summary>
  937. /// 从Unix格式中返回文件信息
  938. /// </summary>
  939. /// <param name="Record">文件信息</param>
  940. private FileStruct ParseFileStructFromUnixStyleRecord(string Record)
  941. {
  942. FileStruct f = new FileStruct();
  943. string processstr = Record.Trim();
  944. f.Flags = processstr.Substring(, );
  945. f.IsDirectory = (f.Flags[] == 'd');
  946. processstr = (processstr.Substring()).Trim();
  947. _cutSubstringFromStringWithTrim(ref processstr, ' ', ); //跳过一部分
  948. f.Owner = _cutSubstringFromStringWithTrim(ref processstr, ' ', );
  949. f.Group = _cutSubstringFromStringWithTrim(ref processstr, ' ', );
  950. _cutSubstringFromStringWithTrim(ref processstr, ' ', ); //跳过一部分
  951. string yearOrTime = processstr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[];
  952. if (yearOrTime.IndexOf(":") >= ) //time
  953. {
  954. processstr = processstr.Replace(yearOrTime, DateTime.Now.Year.ToString());
  955. }
  956. f.CreateTime = DateTime.Parse(_cutSubstringFromStringWithTrim(ref processstr, ' ', ));
  957. f.Name = processstr; //最后就是名称
  958. return f;
  959. }
  960.  
  961. /// <summary>
  962. /// 按照一定的规则进行字符串截取
  963. /// </summary>
  964. /// <param name="s">截取的字符串</param>
  965. /// <param name="c">查找的字符</param>
  966. /// <param name="startIndex">查找的位置</param>
  967. private string _cutSubstringFromStringWithTrim(ref string s, char c, int startIndex)
  968. {
  969. int pos1 = s.IndexOf(c, startIndex);
  970. string retString = s.Substring(, pos1);
  971. s = (s.Substring(pos1)).Trim();
  972. return retString;
  973. }
  974. #endregion
  975. #region 目录或文件存在的判断
  976. /// <summary>
  977. /// 判断当前目录下指定的子目录是否存在
  978. /// </summary>
  979. /// <param name="RemoteDirectoryName">指定的目录名</param>
  980. public bool DirectoryExist(string RemoteDirectoryName)
  981. {
  982. try
  983. {
  984. if (!IsValidPathChars(RemoteDirectoryName))
  985. {
  986. throw new Exception("目录名非法!");
  987. }
  988. FileStruct[] listDir = ListDirectories();
  989. foreach (FileStruct dir in listDir)
  990. {
  991. if (dir.Name == RemoteDirectoryName)
  992. {
  993. return true;
  994. }
  995. }
  996. return false;
  997. }
  998. catch (Exception ep)
  999. {
  1000. ErrorMsg = ep.ToString();
  1001. throw ep;
  1002. }
  1003. }
  1004. /// <summary>
  1005. /// 判断一个远程文件是否存在服务器当前目录下面
  1006. /// </summary>
  1007. /// <param name="RemoteFileName">远程文件名</param>
  1008. public bool FileExist(string RemoteFileName)
  1009. {
  1010. try
  1011. {
  1012. if (!IsValidFileChars(RemoteFileName))
  1013. {
  1014. throw new Exception("文件名非法!");
  1015. }
  1016. FileStruct[] listFile = ListFiles();
  1017. foreach (FileStruct file in listFile)
  1018. {
  1019. if (file.Name == RemoteFileName)
  1020. {
  1021. return true;
  1022. }
  1023. }
  1024. return false;
  1025. }
  1026. catch (Exception ep)
  1027. {
  1028. ErrorMsg = ep.ToString();
  1029. throw ep;
  1030. }
  1031. }
  1032. #endregion
  1033. #region 删除文件
  1034. /// <summary>
  1035. /// 从FTP服务器上面删除一个文件
  1036. /// </summary>
  1037. /// <param name="RemoteFileName">远程文件名</param>
  1038. public void DeleteFile(string RemoteFileName)
  1039. {
  1040. try
  1041. {
  1042. if (!IsValidFileChars(RemoteFileName))
  1043. {
  1044. throw new Exception("文件名非法!");
  1045. }
  1046. Response = Open(new Uri(this.Uri.ToString() + RemoteFileName), WebRequestMethods.Ftp.DeleteFile);
  1047. }
  1048. catch (Exception ep)
  1049. {
  1050. ErrorMsg = ep.ToString();
  1051. throw ep;
  1052. }
  1053. }
  1054. #endregion
  1055. #region 重命名文件
  1056. /// <summary>
  1057. /// 更改一个文件的名称或一个目录的名称
  1058. /// </summary>
  1059. /// <param name="RemoteFileName">原始文件或目录名称</param>
  1060. /// <param name="NewFileName">新的文件或目录的名称</param>
  1061. public bool ReName(string RemoteFileName, string NewFileName)
  1062. {
  1063. try
  1064. {
  1065. if (!IsValidFileChars(RemoteFileName) || !IsValidFileChars(NewFileName))
  1066. {
  1067. throw new Exception("文件名非法!");
  1068. }
  1069. if (RemoteFileName == NewFileName)
  1070. {
  1071. return true;
  1072. }
  1073. if (FileExist(RemoteFileName))
  1074. {
  1075. Request = OpenRequest(new Uri(this.Uri.ToString() + RemoteFileName), WebRequestMethods.Ftp.Rename);
  1076. Request.RenameTo = NewFileName;
  1077. Response = (FtpWebResponse) Request.GetResponse();
  1078.  
  1079. }
  1080. else
  1081. {
  1082. throw new Exception("文件在服务器上不存在!");
  1083. }
  1084. return true;
  1085. }
  1086. catch (Exception ep)
  1087. {
  1088. ErrorMsg = ep.ToString();
  1089. throw ep;
  1090. }
  1091. }
  1092. #endregion
  1093. #region 拷贝、移动文件
  1094. /// <summary>
  1095. /// 把当前目录下面的一个文件拷贝到服务器上面另外的目录中,注意,拷贝文件之后,当前工作目录还是文件原来所在的目录
  1096. /// </summary>
  1097. /// <param name="RemoteFile">当前目录下的文件名</param>
  1098. /// <param name="DirectoryName">新目录名称。
  1099. /// 说明:如果新目录是当前目录的子目录,则直接指定子目录。如: SubDirectory1/SubDirectory2 ;
  1100. /// 如果新目录不是当前目录的子目录,则必须从根目录一级一级的指定。如: ./NewDirectory/SubDirectory1/SubDirectory2
  1101. /// </param>
  1102. /// <returns></returns>
  1103. public bool CopyFileToAnotherDirectory(string RemoteFile, string DirectoryName)
  1104. {
  1105. string CurrentWorkDir = this.DirectoryPath;
  1106. try
  1107. {
  1108. byte[] bt = DownloadFile(RemoteFile);
  1109. GotoDirectory(DirectoryName);
  1110. bool Success = UploadFile(bt, RemoteFile, false);
  1111. this.DirectoryPath = CurrentWorkDir;
  1112. return Success;
  1113. }
  1114. catch (Exception ep)
  1115. {
  1116. this.DirectoryPath = CurrentWorkDir;
  1117. ErrorMsg = ep.ToString();
  1118. throw ep;
  1119. }
  1120. }
  1121. /// <summary>
  1122. /// 把当前目录下面的一个文件移动到服务器上面另外的目录中,注意,移动文件之后,当前工作目录还是文件原来所在的目录
  1123. /// </summary>
  1124. /// <param name="RemoteFile">当前目录下的文件名</param>
  1125. /// <param name="DirectoryName">新目录名称。
  1126. /// 说明:如果新目录是当前目录的子目录,则直接指定子目录。如: SubDirectory1/SubDirectory2 ;
  1127. /// 如果新目录不是当前目录的子目录,则必须从根目录一级一级的指定。如: ./NewDirectory/SubDirectory1/SubDirectory2
  1128. /// </param>
  1129. /// <returns></returns>
  1130. public bool MoveFileToAnotherDirectory(string RemoteFile, string DirectoryName)
  1131. {
  1132. string CurrentWorkDir = this.DirectoryPath;
  1133. try
  1134. {
  1135. if (DirectoryName == "")
  1136. return false;
  1137. if (!DirectoryName.StartsWith("/"))
  1138. DirectoryName = "/" + DirectoryName;
  1139. if (!DirectoryName.EndsWith("/"))
  1140. DirectoryName += "/";
  1141. bool Success = ReName(RemoteFile, DirectoryName + RemoteFile);
  1142. this.DirectoryPath = CurrentWorkDir;
  1143. return Success;
  1144. }
  1145. catch (Exception ep)
  1146. {
  1147. this.DirectoryPath = CurrentWorkDir;
  1148. ErrorMsg = ep.ToString();
  1149. throw ep;
  1150. }
  1151. }
  1152. #endregion
  1153. #region 建立、删除子目录
  1154. /// <summary>
  1155. /// 在FTP服务器上当前工作目录建立一个子目录
  1156. /// </summary>
  1157. /// <param name="DirectoryName">子目录名称</param>
  1158. public bool MakeDirectory(string DirectoryName)
  1159. {
  1160. try
  1161. {
  1162. if (!IsValidPathChars(DirectoryName))
  1163. {
  1164. throw new Exception("目录名非法!");
  1165. }
  1166. if (DirectoryExist(DirectoryName))
  1167. {
  1168. throw new Exception("服务器上面已经存在同名的文件名或目录名!");
  1169. }
  1170. Response = Open(new Uri(this.Uri.ToString() + DirectoryName), WebRequestMethods.Ftp.MakeDirectory);
  1171. return true;
  1172. }
  1173. catch (Exception ep)
  1174. {
  1175. ErrorMsg = ep.ToString();
  1176. throw ep;
  1177. }
  1178. }
  1179. /// <summary>
  1180. /// 从当前工作目录中删除一个子目录
  1181. /// </summary>
  1182. /// <param name="DirectoryName">子目录名称</param>
  1183. public bool RemoveDirectory(string DirectoryName)
  1184. {
  1185. try
  1186. {
  1187. if (!IsValidPathChars(DirectoryName))
  1188. {
  1189. throw new Exception("目录名非法!");
  1190. }
  1191. if (!DirectoryExist(DirectoryName))
  1192. {
  1193. throw new Exception("服务器上面不存在指定的文件名或目录名!");
  1194. }
  1195. Response = Open(new Uri(this.Uri.ToString() + DirectoryName), WebRequestMethods.Ftp.RemoveDirectory);
  1196. return true;
  1197. }
  1198. catch (Exception ep)
  1199. {
  1200. ErrorMsg = ep.ToString();
  1201. throw ep;
  1202. }
  1203. }
  1204. #endregion
  1205. #region 文件、目录名称有效性判断
  1206. /// <summary>
  1207. /// 判断目录名中字符是否合法
  1208. /// </summary>
  1209. /// <param name="DirectoryName">目录名称</param>
  1210. public bool IsValidPathChars(string DirectoryName)
  1211. {
  1212. char[] invalidPathChars = Path.GetInvalidPathChars();
  1213. char[] DirChar = DirectoryName.ToCharArray();
  1214. foreach (char C in DirChar)
  1215. {
  1216. if (Array.BinarySearch(invalidPathChars, C) >= )
  1217. {
  1218. return false;
  1219. }
  1220. }
  1221. return true;
  1222. }
  1223. /// <summary>
  1224. /// 判断文件名中字符是否合法
  1225. /// </summary>
  1226. /// <param name="FileName">文件名称</param>
  1227. public bool IsValidFileChars(string FileName)
  1228. {
  1229. char[] invalidFileChars = Path.GetInvalidFileNameChars();
  1230. char[] NameChar = FileName.ToCharArray();
  1231. foreach (char C in NameChar)
  1232. {
  1233. if (Array.BinarySearch(invalidFileChars, C) >= )
  1234. {
  1235. return false;
  1236. }
  1237. }
  1238. return true;
  1239. }
  1240. #endregion
  1241. #region 目录切换操作
  1242. /// <summary>
  1243. /// 进入一个目录
  1244. /// </summary>
  1245. /// <param name="DirectoryName">
  1246. /// 新目录的名字。
  1247. /// 说明:如果新目录是当前目录的子目录,则直接指定子目录。如: SubDirectory1/SubDirectory2 ;
  1248. /// 如果新目录不是当前目录的子目录,则必须从根目录一级一级的指定。如: ./NewDirectory/SubDirectory1/SubDirectory2
  1249. /// </param>
  1250. public bool GotoDirectory(string DirectoryName)
  1251. {
  1252. string CurrentWorkPath = this.DirectoryPath;
  1253. try
  1254. {
  1255. DirectoryName = DirectoryName.Replace("\\", "/");
  1256. string[] DirectoryNames = DirectoryName.Split(new char[] { '/' });
  1257. if (DirectoryNames[] == ".")
  1258. {
  1259. this.DirectoryPath = "/";
  1260. if (DirectoryNames.Length == )
  1261. {
  1262. return true;
  1263. }
  1264. Array.Clear(DirectoryNames, , );
  1265. }
  1266. bool Success = false;
  1267. foreach (string dir in DirectoryNames)
  1268. {
  1269. if (dir != null)
  1270. {
  1271. Success = EnterOneSubDirectory(dir);
  1272. if (!Success)
  1273. {
  1274. this.DirectoryPath = CurrentWorkPath;
  1275. return false;
  1276. }
  1277. }
  1278. }
  1279. return Success;
  1280.  
  1281. }
  1282. catch (Exception ep)
  1283. {
  1284. this.DirectoryPath = CurrentWorkPath;
  1285. ErrorMsg = ep.ToString();
  1286. throw ep;
  1287. }
  1288. }
  1289. /// <summary>
  1290. /// 从当前工作目录进入一个子目录
  1291. /// </summary>
  1292. /// <param name="DirectoryName">子目录名称</param>
  1293. private bool EnterOneSubDirectory(string DirectoryName)
  1294. {
  1295. try
  1296. {
  1297. if (DirectoryName.IndexOf("/") >= || !IsValidPathChars(DirectoryName))
  1298. {
  1299. throw new Exception("目录名非法!");
  1300. }
  1301. if (DirectoryName.Length > && DirectoryExist(DirectoryName))
  1302. {
  1303. if (!DirectoryName.EndsWith("/"))
  1304. {
  1305. DirectoryName += "/";
  1306. }
  1307. _DirectoryPath += DirectoryName;
  1308. return true;
  1309. }
  1310. else
  1311. {
  1312. return false;
  1313. }
  1314. }
  1315. catch (Exception ep)
  1316. {
  1317. ErrorMsg = ep.ToString();
  1318. throw ep;
  1319. }
  1320. }
  1321. /// <summary>
  1322. /// 从当前工作目录往上一级目录
  1323. /// </summary>
  1324. public bool ComeoutDirectory()
  1325. {
  1326. if (_DirectoryPath == "/")
  1327. {
  1328. ErrorMsg = "当前目录已经是根目录!";
  1329. throw new Exception("当前目录已经是根目录!");
  1330. }
  1331. char[] sp = new char[] { '/' };
  1332.  
  1333. string[] strDir = _DirectoryPath.Split(sp, StringSplitOptions.RemoveEmptyEntries);
  1334. if (strDir.Length == )
  1335. {
  1336. _DirectoryPath = "/";
  1337. }
  1338. else
  1339. {
  1340. _DirectoryPath = String.Join("/", strDir, , strDir.Length - );
  1341. }
  1342. return true;
  1343.  
  1344. }
  1345. #endregion
  1346. #region 重载WebClient,支持FTP进度
  1347. internal class MyWebClient : WebClient
  1348. {
  1349. protected override WebRequest GetWebRequest(Uri address)
  1350. {
  1351. FtpWebRequest req = (FtpWebRequest) base.GetWebRequest(address);
  1352. req.UsePassive = false;
  1353. return req;
  1354. }
  1355. }
  1356. #endregion
  1357. }
  1358. }

ClsFtp

  1. 调用方法,目前只用上传功能:
  2. 定义全局私有变量:
  3. private clsFTP cf;
  4. 按钮事件:
  5. private void btn_upFile_Click(object sender, EventArgs e)
  6. {
  7. lb_upload.Text = "正在上传文件,请等待...";
  8. cf = new clsFTP(new Uri("http://www.cnblogs.com/zhangjun1130/admin/ftp://192.168.43.55/"), "temp", "temp");
  9. string localFile = Application.StartupPath.ToString() + "http://www.cnblogs.com/zhangjun1130/admin/file://output//zt.rar";
  10. cf.UploadProgressChanged+=new clsFTP.De_UploadProgressChanged(cf_UploadProgressChanged);
  11. cf.UploadFileCompleted+=new clsFTP.De_UploadFileCompleted(cf_UploadFileCompleted);
  12. cf.UploadFileAsync(localFile, true); //调用异步传输,若有文件存在则覆盖。
  13. }
  14. 事件捆绑,反映上传进度:
  15. public void cf_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
  16. {
  17. this.pgrBarFileUpload.Maximum = (int)e.TotalBytesToSend;
  18. this.pgrBarFileUpload.Value =(int) e.BytesSent;
  19. lb_upload.Text = string.Format("文件总大小:{0}k,已经上传: {1}k。", e.TotalBytesToSend/,e.BytesSent/);
  20. }
  21. public void cf_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
  22. {
  23. try
  24. {
  25. lb_upload.Text = "无法连接到服务器,或者用户登陆失败!";
  26. lb_error.Text =e.Error.Message.ToString();
  27. }
  28. catch
  29. {
  30. lb_upload.Text = "文件上传成功!";
  31. lb_error.Text = "";
  32. }
  33. }

例子

源文件地址:http://www.cnblogs.com/zhangjun1130/archive/2010/03/24/1693932.html

源文件地址下有详细说明,很详细,大牛!

Ftp类的更多相关文章

  1. 【转】深入PHP FTP类的详解

    FTP是一种文件传输协议,它支持两种模式,一种方式叫做Standard (也就是Active,主动方式),一种是 Passive (也就是PASV,被动方式). Standard模式 FTP 的客户端 ...

  2. PHP操作FTP类 (上传下载移动创建等)

    使用PHP操作FTP-用法 Php代码 收藏代码 <? // 联接FTP服务器 $conn = ftp_connect(ftp.server.com); // 使用username和passwo ...

  3. 一个封装比较完整的FTP类——clsFTP

    前几天,看见园子里面的博友写了一个支持断点续传的FTP类,一时技痒,干脆写了个更完整的clsFtp类.只是我写这个clsFtp不是支持断点续传的目的,而是为了封装FTP几个基本常用的操作接口. 功能 ...

  4. C# 实现 微软WebRequestMethods.Ftp类中的FTP操作功能

    先奉献一个测试地址,ftp内的文件请勿删除,谢谢 FtpEntity fe = "); 由于代码量较多,只抽出一部分,详细代码请移步  ftp://wjshan0808.3vhost.net ...

  5. 封装FTP类

    using System; using System.Net; using System.Net.Sockets; using System.Text; using System.IO; using ...

  6. php的ftp类

    1.需求 了解php的ftp使用 2.例子 使用CI封装好的ftp类库 上传 $this->load->library('ftp'); $config['hostname'] = 'ftp ...

  7. 关于FTP操作的功能类

    自己在用的FTP类,实现了检查FTP链接以及返回FTP没有反应的情况. public delegate void ShowError(string content, string title); // ...

  8. ftp中ftpClient类的API

    org.apache.commons.NET.ftp  Class FTPClient类FTPClient java.lang.Object java.lang.Object继承 org.apache ...

  9. FTP上传文件提示550错误原因分析。

    今天测试FTP上传文件功能,同样的代码从自己的Demo移到正式的代码中,不能实现功能,并报 Stream rs = ftp.GetRequestStream()提示远程服务器返回错误: (550) 文 ...

随机推荐

  1. mysql数据库每日定时自动备份

    使用navicat

  2. wordpress 首页调用文章 不同样式的方法

    <?php $count = 1; $display_categories = array(1); foreach ($display_categories as $category) { ?& ...

  3. 【转】tomcat性能调优

    一.总结前一天的学习 从"第三天"的性能测试一节中,我们得知了决定性能测试的几个重要指标,它们是: ü   吞吐量 ü   Responsetime ü   Cpuload ü   ...

  4. c语言调用函数打印一维数组-2-指针

    方法一(规范): #include <stdio.h> #include <math.h> #include <stdlib.h> //函数预声明 ], int m ...

  5. JavaScript由浅入深(一)——类型、值和变量

      JavaScript是一门面向web的.高端的.动态的.弱类型的编程语言,是学习web前端开发必备的基础技能之一.JavaScript最初是一门脚本语言(scripting-language),它 ...

  6. 如何查看前端部署的tracker代码

    1.www.gov.cn 2.F12>Source>左侧选择static.gridsumdissector.com/js 3.点击代码下方区域的中括号,展开代码preety print{}

  7. jqGrid属性中文详细说明 (转)

    jqGrid的属性很多,其实很大部分的属性,使用其默认值就可以了.但是详细了解一下属性的含义以及作用,对我们定制自己的grid是有帮助的. 以下内容描述格式是:属性名称 参数值类型    描述内容(可 ...

  8. [C++中级进阶]001_C++0x里的完美转发到底是神马?

    [C++中级进阶]001_C++0x里的完美转发到底是神马? 转载至:http://www.cnblogs.com/alephsoul-alephsoul/archive/2013/01/10/285 ...

  9. SIT_服务器系统整合测试总结

    从2012年到2015年我的3年服务器测试,感觉一下子时间就已经飞逝而过,一直希望做个前三年的工作总结,现在用我那笨拙的笔触记录下自己的三年服务器测试生活! ***2012-2013 SE 这一年基本 ...

  10. asp.net C#获取程序文件相关信息

    代码如下 复制代码 using System.Reflection;using System.Runtime.CompilerServices; //// 有关程序集的常规信息是通过下列// 属性集控 ...