/Platters/classes/ftp.cs

http://skimpt.googlecode.com/ · C# · 1134 lines · 840 code · 164 blank · 130 comment · 134 complexity · 8edb33b502b034f6306723bd775ac42f MD5 · raw file

  1. #region "License Agreement"
  2. /* Skimpt, an open source screenshot utility.
  3. Copyright (C) <year> <name of author>
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. this program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  14. #endregion
  15. using System;
  16. using System.Net;
  17. using System.IO;
  18. using System.Text;
  19. using System.Net.Sockets;
  20. using System.Text.RegularExpressions;
  21. using System.Collections;
  22. /// <summary>
  23. /// converted to C# and Modified by Andy Bonner - andybonner@lycos.com
  24. /// Modified on October 24th 2008 by Affan Shoukat to improve performance.
  25. /// </summary>
  26. ///
  27. public class FTP
  28. {
  29. #region "Class Variable Declarations"
  30. private string m_sRemoteHost;
  31. private string m_sRemotePath;
  32. private string m_sRemoteUser;
  33. private string m_sRemotePassword;
  34. // private string m_sMess;
  35. private int m_iRemotePort;
  36. private int m_iBytes;
  37. private Socket m_objClientSocket;
  38. private int m_iRetValue;
  39. private bool m_bLoggedIn;
  40. private string m_sMes;
  41. private string m_sReply;
  42. //Set the size of the packet that is used to read and to write data to the FTP server
  43. //to the following specified size.
  44. public const int BLOCK_SIZE = 512;
  45. private byte[] m_aBuffer = new byte[BLOCK_SIZE + 1];
  46. private Encoding ASCII = Encoding.ASCII;
  47. public bool flag_bool;
  48. //General variable declaration
  49. private string m_sMessageString;
  50. #endregion
  51. #region " Constructors "
  52. public FTP()
  53. {
  54. m_sRemoteHost = "microsoft";
  55. m_sRemotePath = ".";
  56. m_sRemoteUser = "anonymous";
  57. m_sRemotePassword = "";
  58. m_sMessageString = "";
  59. m_iRemotePort = 21;
  60. m_bLoggedIn = false;
  61. }
  62. public FTP(string sRemoteHost, string sRemotePath,
  63. string sRemoteUser, string sRemotePassword, int iRemotePort)
  64. {
  65. m_sRemoteHost = sRemoteHost;
  66. m_sRemotePath = sRemotePath;
  67. m_sRemoteUser = sRemoteUser;
  68. m_sRemotePassword = sRemotePassword;
  69. m_sMessageString = "";
  70. m_iRemotePort = iRemotePort;
  71. m_bLoggedIn = false;
  72. }
  73. public FTP(string sRemoteHost, string sRemotePath,
  74. string sRemoteUser, string sRemotePassword)
  75. {
  76. m_sRemoteHost = sRemoteHost;
  77. m_sRemotePath = sRemotePath;
  78. m_sRemoteUser = sRemoteUser;
  79. m_sRemotePassword = sRemotePassword;
  80. m_sMessageString = "";
  81. m_iRemotePort = 21;
  82. m_bLoggedIn = false;
  83. }
  84. #endregion
  85. #region " Public Properties "
  86. /// Set or Get the name of the FTP server that you want to connect to.
  87. public string RemoteHostFTPServer
  88. {
  89. get { return m_sRemoteHost; }
  90. set { m_sRemoteHost = value; }
  91. }
  92. /// Set or Get the FTP port number of the FTP server that you want to connect to.
  93. public int RemotePort
  94. {
  95. get { return m_iRemotePort; }
  96. set { m_iRemotePort = value; }
  97. }
  98. /// Set or Get the remote path of the FTP server that you want to connect to.
  99. public string RemotePath
  100. {
  101. get { return m_sRemotePath; }
  102. set { m_sRemotePath = value; }
  103. }
  104. /// Set the remote password of the FTP server that you want to connect to.
  105. public string RemotePassword
  106. {
  107. get { return m_sRemotePassword; }
  108. set { m_sRemotePassword = value; }
  109. }
  110. /// Set or Get the remote user of the FTP server that you want to connect to.
  111. public string RemoteUser
  112. {
  113. get { return m_sRemoteUser; }
  114. set { m_sRemoteUser = value; }
  115. }
  116. /// Set or Get the class messagestring.
  117. public string MessageString
  118. {
  119. get { return m_sMessageString; }
  120. set { m_sMessageString = value; }
  121. }
  122. #endregion
  123. #region " Public Subs and Functions "
  124. /// Return a list of files from the file system. Return these files in a string() array.
  125. public string[] GetFileList(string sMask)
  126. {
  127. Socket cSocket;
  128. int bytes;
  129. char seperator = Convert.ToChar("\n");
  130. string[] mess;
  131. m_sMes = "";
  132. /// Check to see if you are logged on to the FTP server.
  133. if (!m_bLoggedIn)
  134. {
  135. Login();
  136. }
  137. cSocket = CreateDataSocket();
  138. /// Send an FTP command.
  139. SendCommand("NLST " + sMask);
  140. if (!(m_iRetValue == 150 || m_iRetValue == 125))
  141. {
  142. MessageString = m_sReply;
  143. throw new IOException(m_sReply.Substring(4));
  144. }
  145. m_sMes = "";
  146. while (true)
  147. {
  148. Array.Clear(m_aBuffer, 0, m_aBuffer.Length);
  149. bytes = cSocket.Receive(m_aBuffer, m_aBuffer.Length, 0);
  150. m_sMes += ASCII.GetString(m_aBuffer, 0, bytes);
  151. if (bytes < m_aBuffer.Length)
  152. {
  153. break;
  154. }
  155. System.Threading.Thread.Sleep(10);
  156. }
  157. mess = m_sMes.Split(seperator);
  158. cSocket.Close();
  159. ReadReply();
  160. if (m_iRetValue != 226)
  161. {
  162. MessageString = m_sReply;
  163. throw new IOException(m_sReply.Substring(4));
  164. }
  165. return mess;
  166. }
  167. private struct SplitLine
  168. {
  169. public bool Valid;
  170. public bool Dir;
  171. public string FileName;
  172. public int FileSize;
  173. public string FileDate;
  174. public string FileTime;
  175. }
  176. /// Return a list of files & Directories from the file system.
  177. public void GetDirList(DirList dl)
  178. {
  179. Socket cSocket;
  180. int bytes;
  181. char seperator = Convert.ToChar("\n");
  182. string[] mess;
  183. m_sMes = "";
  184. /// Check to see if you are logged on to the FTP server.
  185. if (!m_bLoggedIn)
  186. {
  187. Login();
  188. }
  189. cSocket = CreateDataSocket();
  190. /// Send an FTP command.
  191. SendCommand("LIST -AL");
  192. if (!(m_iRetValue == 150 || m_iRetValue == 125))
  193. {
  194. MessageString = m_sReply;
  195. throw new IOException(m_sReply.Substring(4));
  196. }
  197. m_sMes = "";
  198. while (true)
  199. {
  200. Array.Clear(m_aBuffer, 0, m_aBuffer.Length);
  201. bytes = cSocket.Receive(m_aBuffer, m_aBuffer.Length, 0);
  202. m_sMes += ASCII.GetString(m_aBuffer, 0, bytes);
  203. if (bytes < m_aBuffer.Length)
  204. {
  205. break;
  206. }
  207. System.Threading.Thread.Sleep(10);
  208. }
  209. mess = m_sMes.Split(seperator);
  210. cSocket.Close();
  211. ReadReply();
  212. if (m_iRetValue != 226)
  213. {
  214. MessageString = m_sReply;
  215. throw new IOException(m_sReply.Substring(4));
  216. }
  217. if (mess.Length > 0)
  218. {
  219. foreach (string tmpstr in mess)
  220. {
  221. if (tmpstr != "")
  222. {
  223. DirFile lf;
  224. SplitLine sl = ParseLine(tmpstr);
  225. if (sl.Valid)
  226. {
  227. if (sl.Dir)
  228. {
  229. lf = new DirFile(sl.FileName, sl.FileDate, sl.FileTime, true, 0);
  230. }
  231. else
  232. {
  233. lf = new DirFile(sl.FileName, sl.FileDate, sl.FileTime, false, sl.FileSize);
  234. }
  235. dl.Add(lf);
  236. }
  237. }
  238. }
  239. }
  240. }
  241. private SplitLine ParseLine(string Line)
  242. {
  243. SplitLine sl = new SplitLine();
  244. sl.Valid = false;
  245. Regex rx;
  246. Match m;
  247. // is it dos format?
  248. rx = new Regex(@"(?<Date>[0-9|-]{8})\s*(?<Time>[0-9|:|AM|PM]*)\s*(?<Size>[0-9"
  249. + @"|\<|\>|DIR]*)\s*(?<Name>.*)\r", RegexOptions.IgnoreCase);
  250. m = rx.Match(Line);
  251. if (m.Success)
  252. {
  253. sl.Valid = true;
  254. if (m.Groups["Size"].Value == "<DIR>")
  255. {
  256. sl.Dir = true;
  257. sl.FileSize = 0;
  258. }
  259. else
  260. {
  261. sl.Dir = false;
  262. sl.FileSize = Convert.ToInt32(m.Groups["Size"].Value);
  263. }
  264. sl.FileName = m.Groups["Name"].Value;
  265. sl.FileDate = m.Groups["Date"].Value;
  266. sl.FileTime = m.Groups["Time"].Value;
  267. }
  268. else
  269. {
  270. // is it unix format?
  271. rx = new Regex(@"(?<Dir>.{1}).{9}\s*[0-9]*\s*\w*\s*\w*\s*(?<Size>[0-9]*)\s*(?"
  272. + @"<Month>[a-z|A-Z]{3})\s*(?<Day>[0-9]*)\s*(?<Time>[0-9|:]*)\s*("
  273. + @"?<Name>.*)\r", RegexOptions.None);
  274. m = rx.Match(Line);
  275. if (m.Success)
  276. {
  277. sl.Valid = true;
  278. if (m.Groups["Dir"].Value == "d")
  279. {
  280. sl.Dir = true;
  281. }
  282. else
  283. {
  284. sl.Dir = false;
  285. }
  286. sl.FileSize = Convert.ToInt32(m.Groups["Size"].Value);
  287. sl.FileName = m.Groups["Name"].Value;
  288. if (m.Groups["Time"].Value.IndexOf(':') == -1)
  289. {
  290. sl.FileDate = m.Groups["Day"].Value + " " + m.Groups["Month"].Value + " " + m.Groups["Time"].Value;
  291. sl.FileTime = "";
  292. }
  293. else
  294. {
  295. sl.FileDate = m.Groups["Day"].Value + " " + m.Groups["Month"].Value + " " + DateTime.Now.Year.ToString();
  296. sl.FileTime = m.Groups["Time"].Value;
  297. }
  298. }
  299. }
  300. return sl;
  301. }
  302. /// Get the size of the file on the FTP server.
  303. public long GetFileSize(string sFileName)
  304. {
  305. long size;
  306. if (!m_bLoggedIn)
  307. {
  308. Login();
  309. }
  310. /// Send an FTP command.
  311. SendCommand("SIZE " + sFileName);
  312. size = 0;
  313. if (m_iRetValue == 213)
  314. {
  315. size = long.Parse(m_sReply.Substring(4));
  316. }
  317. else
  318. {
  319. MessageString = m_sReply;
  320. throw new IOException(m_sReply.Substring(4));
  321. }
  322. return size;
  323. }
  324. /// Log on to the FTP server.
  325. public bool Login()
  326. {
  327. m_objClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  328. IPEndPoint ep = new IPEndPoint(Dns.Resolve(m_sRemoteHost).AddressList[0], m_iRemotePort);
  329. try
  330. {
  331. m_objClientSocket.Connect(ep);
  332. }
  333. catch (Exception)
  334. {
  335. MessageString = m_sReply;
  336. throw new IOException("Cannot connect to the remote server");
  337. }
  338. ReadReply();
  339. if (m_iRetValue != 220)
  340. {
  341. CloseConnection();
  342. MessageString = m_sReply;
  343. throw new IOException(m_sReply.Substring(4));
  344. }
  345. /// Send an FTP command to send a user logon ID to the server.
  346. SendCommand("USER " + m_sRemoteUser);
  347. if (!(m_iRetValue == 331 || m_iRetValue == 230))
  348. {
  349. Cleanup();
  350. MessageString = m_sReply;
  351. throw new IOException(m_sReply.Substring(4));
  352. }
  353. if (m_iRetValue != 230)
  354. {
  355. ///Send an FTP command to send a user logon password to the server.
  356. SendCommand("PASS " + m_sRemotePassword);
  357. if (!(m_iRetValue == 230 || m_iRetValue == 202))
  358. {
  359. Cleanup();
  360. MessageString = m_sReply;
  361. throw new IOException(m_sReply.Substring(4));
  362. }
  363. }
  364. m_bLoggedIn = true;
  365. /// Call the ChangeDirectory user-defined function to change the directory to the
  366. /// remote FTP folder that is mapped.
  367. ChangeDirectory(m_sRemotePath);
  368. /// Return the final result.
  369. return m_bLoggedIn;
  370. }
  371. /// If the value of mode is true, set binary mode for downloads. Otherwise, set ASCII mode.
  372. public void SetBinaryMode(bool bMode)
  373. {
  374. if (bMode)
  375. {
  376. /// Send the FTP command to set the binary mode.
  377. /// (TYPE is an FTP command that is used to specify representation type.)
  378. SendCommand("TYPE I");
  379. }
  380. else
  381. {
  382. /// Send the FTP command to set ASCII mode.
  383. /// (TYPE is an FTP command that is used to specify representation type.)
  384. SendCommand("TYPE A");
  385. }
  386. if (m_iRetValue != 200)
  387. {
  388. MessageString = m_sReply;
  389. throw new IOException(m_sReply.Substring(4));
  390. }
  391. }
  392. /// Download a file to the local directory of the assembly. Keep the same file name.
  393. public void DownloadFile(string sFileName)
  394. {
  395. DownloadFile(sFileName, "", false);
  396. }
  397. /// Download a remote file to the local directory of the Assembly. Keep the same file name.
  398. public void DownloadFile(string sFileName, bool bResume)
  399. {
  400. DownloadFile(sFileName, "", bResume);
  401. }
  402. /// Download a remote file to a local file name. You must include a path.
  403. /// The local file name will be created or will be overwritten, but the path must exist.
  404. public void DownloadFile(string sFileName, string sLocalFileName)
  405. {
  406. DownloadFile(sFileName, sLocalFileName, false);
  407. }
  408. /// Download a remote file to a local file name. You must include a path. Set the
  409. /// resume flag. The local file name will be created or will be overwritten, but the path must exist.
  410. public void DownloadFile(string sFileName, string sLocalFileName, bool bResume)
  411. {
  412. Stream st;
  413. FileStream output;
  414. Socket cSocket;
  415. long offset;
  416. //long npos;
  417. if (!m_bLoggedIn)
  418. {
  419. Login();
  420. }
  421. SetBinaryMode(true);
  422. if (sLocalFileName.Equals(""))
  423. {
  424. sLocalFileName = sFileName;
  425. }
  426. if (!File.Exists(sLocalFileName))
  427. {
  428. st = File.Create(sLocalFileName);
  429. st.Close();
  430. }
  431. output = new FileStream(sLocalFileName, FileMode.Open);
  432. cSocket = CreateDataSocket();
  433. offset = 0;
  434. if (bResume)
  435. {
  436. offset = output.Length;
  437. if (offset > 0)
  438. {
  439. /// Send an FTP command to restart.
  440. SendCommand("REST " + offset);
  441. if (m_iRetValue != 350)
  442. {
  443. offset = 0;
  444. }
  445. }
  446. if (offset > 0)
  447. {
  448. //npos = output.Seek(offset, SeekOrigin.Begin);
  449. }
  450. }
  451. /// Send an FTP command to retrieve a file.
  452. SendCommand("RETR " + sFileName);
  453. if (!(m_iRetValue == 150 || m_iRetValue == 125))
  454. {
  455. MessageString = m_sReply;
  456. throw new IOException(m_sReply.Substring(4));
  457. }
  458. while (true)
  459. {
  460. Array.Clear(m_aBuffer, 0, m_aBuffer.Length);
  461. m_iBytes = cSocket.Receive(m_aBuffer, m_aBuffer.Length, 0);
  462. output.Write(m_aBuffer, 0, m_iBytes);
  463. if (m_iBytes <= 0)
  464. {
  465. break;
  466. }
  467. }
  468. output.Close();
  469. if (cSocket.Connected)
  470. {
  471. cSocket.Close();
  472. }
  473. ReadReply();
  474. if (!(m_iRetValue == 226 || m_iRetValue == 250))
  475. {
  476. MessageString = m_sReply;
  477. throw new IOException(m_sReply.Substring(4));
  478. }
  479. }
  480. /// This is a function that is used to upload a file from your local hard disk
  481. /// to your FTP site.
  482. public void UploadFile(string sFileName)
  483. {
  484. UploadFile(sFileName, false);
  485. }
  486. /// This is a function that is used to upload a file from your local hard disk
  487. /// to your FTP site and then set the resume flag.
  488. public void UploadFile(string sFileName, bool bResume)
  489. {
  490. Socket cSocket;
  491. long offset;
  492. FileStream input;
  493. bool bFileNotFound;
  494. if (!m_bLoggedIn)
  495. {
  496. Login();
  497. }
  498. cSocket = CreateDataSocket();
  499. offset = 0;
  500. if (bResume)
  501. {
  502. try
  503. {
  504. SetBinaryMode(true);
  505. offset = GetFileSize(sFileName);
  506. }
  507. catch (Exception)
  508. {
  509. offset = 0;
  510. }
  511. }
  512. if (offset > 0)
  513. {
  514. SendCommand("REST " + offset);
  515. if (m_iRetValue != 350)
  516. {
  517. /// The remote server may not support resuming.
  518. offset = 0;
  519. }
  520. }
  521. /// Send an FTP command to store a file.
  522. SendCommand("STOR " + Path.GetFileName(sFileName));
  523. if (!(m_iRetValue == 125 || m_iRetValue == 150))
  524. {
  525. MessageString = m_sReply;
  526. throw new IOException(m_sReply.Substring(4));
  527. }
  528. /// Check to see if the file exists before the upload.
  529. bFileNotFound = false;
  530. if (File.Exists(sFileName))
  531. {
  532. /// Open the input stream to read the source file.
  533. input = new FileStream(sFileName, FileMode.Open);
  534. if (offset != 0)
  535. {
  536. input.Seek(offset, SeekOrigin.Begin);
  537. }
  538. /// Upload the file.
  539. m_iBytes = input.Read(m_aBuffer, 0, m_aBuffer.Length);
  540. while (m_iBytes > 0)
  541. {
  542. cSocket.Send(m_aBuffer, m_iBytes, 0);
  543. m_iBytes = input.Read(m_aBuffer, 0, m_aBuffer.Length);
  544. }
  545. input.Close();
  546. }
  547. else
  548. {
  549. bFileNotFound = true;
  550. }
  551. if (cSocket.Connected)
  552. {
  553. cSocket.Close();
  554. }
  555. /// Check the return value if the file was not found.
  556. if (bFileNotFound)
  557. {
  558. MessageString = m_sReply;
  559. throw new IOException("The file: " + sFileName + " was not found. Cannot upload the file to the FTP site");
  560. }
  561. ReadReply();
  562. if (!(m_iRetValue == 226 || m_iRetValue == 250))
  563. {
  564. MessageString = m_sReply;
  565. throw new IOException(m_sReply.Substring(4));
  566. }
  567. }
  568. /// Delete a file from the remote FTP server.
  569. public bool DeleteFile(string sFileName)
  570. {
  571. bool bResult;
  572. bResult = true;
  573. if (!m_bLoggedIn)
  574. {
  575. Login();
  576. }
  577. /// Send an FTP command to delete a file.
  578. SendCommand("DELE " + sFileName);
  579. if (m_iRetValue != 250)
  580. {
  581. bResult = false;
  582. MessageString = m_sReply;
  583. }
  584. /// Return the final result.
  585. return bResult;
  586. }
  587. /// Rename a file on the remote FTP server.
  588. public bool RenameFile(string sOldFileName, string sNewFileName)
  589. {
  590. bool bResult = true;
  591. if (!m_bLoggedIn)
  592. {
  593. Login();
  594. }
  595. /// Send an FTP command to rename from a file.
  596. SendCommand("RNFR " + sOldFileName);
  597. if (m_iRetValue != 350)
  598. {
  599. MessageString = m_sReply;
  600. throw new IOException(m_sReply.Substring(4));
  601. }
  602. /// Send an FTP command to rename a file to a new file name.
  603. /// It will overwrite if newFileName exists.
  604. SendCommand("RNTO " + sNewFileName);
  605. if (m_iRetValue != 250)
  606. {
  607. MessageString = m_sReply;
  608. throw new IOException(m_sReply.Substring(4));
  609. }
  610. /// Return the final result.
  611. return bResult;
  612. }
  613. /// This is a function that is used to create a directory on
  614. /// the remote FTP server.
  615. public bool CreateDirectory(string sDirName)
  616. {
  617. bool bResult = true;
  618. if (!m_bLoggedIn)
  619. {
  620. Login();
  621. }
  622. /// Send an FTP command to make directory on the FTP server.
  623. SendCommand("MKD " + sDirName);
  624. if (m_iRetValue != 257)
  625. {
  626. bResult = false;
  627. MessageString = m_sReply;
  628. }
  629. /// Return the final result.
  630. return bResult;
  631. }
  632. /// This is a function that is used to delete a directory on
  633. /// the remote FTP server.
  634. public bool RemoveDirectory(string sDirName)
  635. {
  636. bool bResult = true;
  637. /// Check if logged on to the FTP server
  638. if (!m_bLoggedIn)
  639. {
  640. Login();
  641. }
  642. /// Send an FTP command to remove directory on the FTP server.
  643. SendCommand("RMD " + sDirName);
  644. if (m_iRetValue != 250)
  645. {
  646. bResult = false;
  647. MessageString = m_sReply;
  648. }
  649. /// Return the final result.
  650. return bResult;
  651. }
  652. /// This is a function that is used to change the current working
  653. /// directory on the remote FTP server.
  654. public bool ChangeDirectory(string sDirName)
  655. {
  656. bool bResult = true;
  657. /// Check if you are in the root directory.
  658. if (sDirName.Equals("."))
  659. {
  660. return false;
  661. }
  662. /// Check if logged on to the FTP server
  663. if (!m_bLoggedIn)
  664. {
  665. Login();
  666. }
  667. /// Send an FTP command to change directory on the FTP server.
  668. SendCommand("CWD " + sDirName);
  669. if (m_iRetValue != 250)
  670. {
  671. bResult = false;
  672. MessageString = m_sReply;
  673. throw new DirectoryNotFoundException("Cannot find directory : " + sDirName);
  674. }
  675. m_sRemotePath = sDirName;
  676. /// Return the final result.
  677. return bResult;
  678. }
  679. /// Close the FTP connection of the remote server.
  680. public void CloseConnection()
  681. {
  682. if (m_objClientSocket != null)
  683. {
  684. /// Send an FTP command to end an FTP server system.
  685. SendCommand("QUIT");
  686. }
  687. Cleanup();
  688. }
  689. #endregion
  690. #region " Private Subs and Functions "
  691. /// Read the reply from the FTP server.
  692. private void ReadReply()
  693. {
  694. m_sMes = "";
  695. m_sReply = ReadLine(false);
  696. m_iRetValue = int.Parse(m_sReply.Substring(0, 3));
  697. }
  698. /// Clean up some variables.
  699. private void Cleanup()
  700. {
  701. if (m_objClientSocket != null)
  702. {
  703. m_objClientSocket.Close();
  704. m_objClientSocket = null;
  705. }
  706. m_bLoggedIn = false;
  707. }
  708. /// Read a line from the FTP server.
  709. private string ReadLine(bool bClearMes)
  710. {
  711. char seperator = Convert.ToChar("\n");
  712. string[] mess;
  713. if (bClearMes)
  714. {
  715. m_sMes = "";
  716. }
  717. while (true)
  718. {
  719. Array.Clear(m_aBuffer, 0, BLOCK_SIZE);
  720. m_iBytes = m_objClientSocket.Receive(m_aBuffer, m_aBuffer.Length, 0);
  721. m_sMes += ASCII.GetString(m_aBuffer, 0, m_iBytes);
  722. if (m_iBytes < m_aBuffer.Length)
  723. {
  724. break;
  725. }
  726. }
  727. mess = m_sMes.Split(seperator);
  728. if (m_sMes.Length > 2)
  729. {
  730. m_sMes = mess[mess.Length - 2];
  731. }
  732. else
  733. {
  734. m_sMes = mess[0];
  735. }
  736. if (!m_sMes.Substring(3, 1).Equals(" "))
  737. {
  738. return ReadLine(true);
  739. }
  740. return m_sMes;
  741. }
  742. /// This is a function that is used to send a command to the FTP server that you are connected to.
  743. private void SendCommand(string sCommand)
  744. {
  745. sCommand = sCommand + "\r\n";
  746. byte[] cmdbytes = ASCII.GetBytes(sCommand);
  747. m_objClientSocket.Send(cmdbytes, cmdbytes.Length, 0);
  748. ReadReply();
  749. }
  750. /// Create a data socket.
  751. private Socket CreateDataSocket()
  752. {
  753. int index1;
  754. int index2;
  755. int len;
  756. int partCount;
  757. int i;
  758. int port;
  759. string ipData;
  760. string buf;
  761. string ipAddress;
  762. int[] parts = new int[7];
  763. char ch;
  764. Socket s;
  765. IPEndPoint ep;
  766. /// Send an FTP command to use passive data connection.
  767. SendCommand("PASV");
  768. if (m_iRetValue != 227)
  769. {
  770. MessageString = m_sReply;
  771. throw new IOException(m_sReply.Substring(4));
  772. }
  773. index1 = m_sReply.IndexOf("(");
  774. index2 = m_sReply.IndexOf(")");
  775. ipData = m_sReply.Substring(index1 + 1, index2 - index1 - 1);
  776. len = ipData.Length;
  777. partCount = 0;
  778. buf = "";
  779. for (i = 0; i <= (len - 1); i++)
  780. {
  781. if (partCount > 6)
  782. {
  783. break;
  784. }
  785. ch = char.Parse(ipData.Substring(i, 1));
  786. if (char.IsDigit(ch))
  787. {
  788. buf += ch;
  789. }
  790. else if (ch != Convert.ToChar(","))
  791. {
  792. MessageString = m_sReply;
  793. throw new IOException("Malformed PASV reply: " + m_sReply);
  794. }
  795. if ((ch == Convert.ToChar(",")) | (i + 1 == len))
  796. {
  797. try
  798. {
  799. parts[partCount] = int.Parse(buf);
  800. partCount += 1;
  801. buf = "";
  802. }
  803. catch (Exception)
  804. {
  805. MessageString = m_sReply;
  806. throw new IOException("Malformed PASV reply: " + m_sReply);
  807. }
  808. }
  809. }
  810. ipAddress = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3];
  811. /// Make this call in Visual Basic .NET 2002. You want to
  812. /// bitshift the number by 8 bits. In Visual Basic .NET 2002 you must
  813. /// multiply the number by 2 to the power of 8.
  814. /// port = parts(4) * (2 ^ 8)
  815. /// Make this call and then comment out the previous line for
  816. /// Visual Basic .NET 2003.
  817. port = parts[4] << 8;
  818. /// Determine the data port number.
  819. port = port + parts[5];
  820. s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  821. ep = new IPEndPoint(Dns.Resolve(ipAddress).AddressList[0], port);
  822. try
  823. {
  824. s.Connect(ep);
  825. }
  826. catch (Exception)
  827. {
  828. MessageString = m_sReply;
  829. flag_bool = false;
  830. throw new IOException("Cannot connect to remote server.");
  831. /// If you cannot connect to the FTP server that is
  832. /// specified, make the boolean variable false.
  833. }
  834. /// If you can connect to the FTP server that is specified,
  835. /// make the boolean variable true.
  836. flag_bool = true;
  837. return s;
  838. }
  839. #endregion
  840. }
  841. public class DirFile : IComparable
  842. {
  843. private string _Name;
  844. private bool _IsDir;
  845. private string _Date;
  846. private string _Time;
  847. private int _Size;
  848. public string Name { get { return _Name; } }
  849. public bool IsDir { get { return _IsDir; } }
  850. public string FileDate { get { return _Date; } }
  851. public string FileTime { get { return _Time; } }
  852. public int FileSize { get { return _Size; } }
  853. public DirFile(string Name, string FDate, string FTime, bool Dir, int FSize)
  854. {
  855. _Name = Name;
  856. _Date = FDate;
  857. _Time = FTime;
  858. _IsDir = Dir;
  859. _Size = FSize;
  860. }
  861. public int CompareTo(object obj)
  862. {
  863. DirFile df;
  864. // Any non-Nothing object is greater than nothing.
  865. if (obj == null)
  866. {
  867. return 1;
  868. }
  869. // Avoid late-binding and cast to a specific Person Object.
  870. df = ((DirFile)(obj));
  871. // Use the String's CompareTo Method to perform the check.
  872. return this.IsDir.CompareTo(df.IsDir);
  873. }
  874. }
  875. public class DirList : CollectionBase
  876. {
  877. // Create the Default Property Item for this collection.
  878. // Allow the retrieval by index.
  879. public DirFile this[int index]
  880. {
  881. get
  882. {
  883. // Avoid Late-binding and return this as a DirFile Object
  884. return ((DirFile)(this.InnerList[index]));
  885. }
  886. }
  887. // Create another default property for this collection.
  888. // Allow retrieval by name.
  889. public DirFile this[string Instance]
  890. {
  891. get
  892. {
  893. DirFile df;
  894. foreach (DirFile tempLoopVar_df in this.InnerList)
  895. {
  896. df = tempLoopVar_df;
  897. if (df.Name == Instance)
  898. {
  899. // We found our DirFile object, return it.
  900. return df;
  901. }
  902. }
  903. return null;
  904. }
  905. }
  906. // Create another property for this collection.
  907. // Allows checking for existance by name.
  908. bool Exists(string Instance)
  909. {
  910. DirFile df;
  911. foreach (DirFile tempLoopVar_df in this.InnerList)
  912. {
  913. df = tempLoopVar_df;
  914. if (df.Name == Instance)
  915. {
  916. // We found our DirFile object, return it.
  917. return true;
  918. }
  919. }
  920. return false;
  921. }
  922. // Create a new instance of our Collection, by calling MyBase.New
  923. public DirList()
  924. {
  925. }
  926. protected override void OnSet(int index, object oldValue, object newValue)
  927. {
  928. if (!(newValue is DirFile))
  929. {
  930. throw (new ArgumentException(string.Format("Cannot add a {0} type to this collection", newValue.GetType().ToString()), "Value"));
  931. }
  932. }
  933. protected override void OnInsert(int index, object value)
  934. {
  935. if (!(value is DirFile))
  936. {
  937. throw (new ArgumentException(string.Format("Cannot add a {0} type to this collection", value.GetType().ToString()), "Value"));
  938. }
  939. }
  940. protected override void OnRemove(int index, object value)
  941. {
  942. if (!(value is DirFile))
  943. {
  944. throw (new ArgumentException(string.Format("Cannot add a {0} type to this collection", value.GetType().ToString()), "Value"));
  945. }
  946. }
  947. // Method to add a single DirFile object to our collection.
  948. public int Add(DirFile value)
  949. {
  950. return this.InnerList.Add(value);
  951. }
  952. // Method to Remove a specific DirFile object from our collection.
  953. public void Remove(DirFile value)
  954. {
  955. this.InnerList.Remove(value);
  956. }
  957. // Method to check if a DirFile object already exists in the collection.
  958. public bool Contains(DirFile value)
  959. {
  960. return this.Contains(value);
  961. }
  962. // Create the Sort method for the collection.
  963. public void Sort()
  964. {
  965. this.InnerList.Sort();
  966. }
  967. }