Guest User

Untitled

a guest
Nov 12th, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 46.80 KB | None | 0 0
  1. #if DEBUG
  2. #define FTP_DEBUG
  3. #endif
  4.  
  5. #region
  6. using System;
  7. using System.Collections;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Net;
  11. using System.Net.Sockets;
  12. using System.Runtime.InteropServices;
  13. using System.Text;
  14. using System.Text.RegularExpressions;
  15. using System.Threading;
  16. using WaitForm;
  17.  
  18. #endregion
  19.  
  20. namespace WM
  21. {
  22. public class FTP: IDisposable
  23. {
  24. #region Public Variables
  25. /// <summary>
  26. /// Password for account
  27. /// </summary>
  28. public string pass;
  29.  
  30. /// <summary>
  31. /// Port number the FTP server is listening on
  32. /// </summary>
  33. public int port;
  34.  
  35. /// <summary>
  36. /// IP address or hostname to connect to
  37. /// </summary>
  38. public string server;
  39.  
  40. /// <summary>
  41. /// The timeout (miliseconds) for waiting on data to arrive
  42. /// </summary>
  43. public int timeout;
  44.  
  45. /// <summary>
  46. /// Username to login as
  47. /// </summary>
  48. public string user;
  49. #endregion
  50.  
  51. #region Private Variables
  52. private bool _noFrame; // #######################################
  53. private string bucket;
  54. private long bytes_tail; // upload/download info if the user wants it.
  55. private long bytes_total; // upload/download info if the user wants it.
  56. private IPEndPoint data_ipEndPoint;
  57. private Socket data_sock;
  58. private FileStream file;
  59. private long file_size; // gets set when an upload or download takes place
  60. private int kbPerSec;
  61. private Socket listening_sock;
  62. private IPEndPoint main_ipEndPoint;
  63. private Socket main_sock;
  64. private string messages; // server messages
  65. private long packages_sent;
  66. private bool passive_mode; // #######################################
  67. private int response;
  68. private string responseStr; // server response if the user wants it.
  69.  
  70. private DateTime tailtime; //headtime;
  71. private TimeSpan timeTaken;
  72. #endregion
  73.  
  74. #region Constructors
  75. /// <summary>
  76. /// Constructor
  77. /// </summary>
  78. public FTP() {
  79. server = null;
  80. user = null;
  81. pass = null;
  82. port = 21;
  83. passive_mode = true; // #######################################
  84. main_sock = null;
  85. main_ipEndPoint = null;
  86. listening_sock = null;
  87. data_sock = null;
  88. data_ipEndPoint = null;
  89. file = null;
  90. bucket = "";
  91. bytes_total = 0;
  92. timeout = 30000; // 30 seconds
  93. messages = "";
  94. }
  95.  
  96. /// <summary>
  97. /// Constructor
  98. /// </summary>
  99. /// <param name="server">Server to connect to</param>
  100. /// <param name="user">Account to login as</param>
  101. /// <param name="pass">Account password</param>
  102. public FTP(string server, string user, string pass) {
  103. this.server = server;
  104. this.user = user;
  105. this.pass = pass;
  106. port = 21;
  107. passive_mode = true; // #######################################
  108. main_sock = null;
  109. main_ipEndPoint = null;
  110. listening_sock = null;
  111. data_sock = null;
  112. data_ipEndPoint = null;
  113. file = null;
  114. bucket = "";
  115. bytes_total = 0;
  116. timeout = 30000; // 30 seconds
  117. messages = "";
  118. }
  119.  
  120. /// <summary>
  121. /// Constructor
  122. /// </summary>
  123. /// <param name="server">Server to connect to</param>
  124. /// <param name="port">Port server is listening on</param>
  125. /// <param name="user">Account to login as</param>
  126. /// <param name="pass">Account password</param>
  127. public FTP(string server, int port, string user, string pass) {
  128. this.server = server;
  129. this.user = user;
  130. this.pass = pass;
  131. this.port = port;
  132. passive_mode = true; // #######################################
  133. main_sock = null;
  134. main_ipEndPoint = null;
  135. listening_sock = null;
  136. data_sock = null;
  137. data_ipEndPoint = null;
  138. file = null;
  139. bucket = "";
  140. bytes_total = 0;
  141. timeout = 30000; // 30 seconds
  142. messages = "";
  143. }
  144. #endregion
  145.  
  146. /// <summary>
  147. /// Connection status to the server
  148. /// </summary>
  149. public bool IsConnected {
  150. get {
  151. if (main_sock != null)
  152. return main_sock.Connected;
  153. return false;
  154. }
  155. }
  156.  
  157. /// <summary>
  158. /// Returns true if the message buffer has data in it
  159. /// </summary>
  160. public bool MessagesAvailable {
  161. get {
  162. if (messages.Length > 0)
  163. return true;
  164. return false;
  165. }
  166. }
  167.  
  168. /// <summary>
  169. /// Server messages if any, buffer is cleared after you access this property
  170. /// </summary>
  171. public string Messages {
  172. get {
  173. string tmp = messages;
  174. messages = "";
  175. return tmp;
  176. }
  177. }
  178.  
  179. /// <summary>
  180. /// The response string from the last issued command
  181. /// </summary>
  182. public string ResponseString {
  183. get { return responseStr; }
  184. }
  185.  
  186. /// <summary>
  187. /// The total number of bytes sent/recieved in a transfer
  188. /// </summary>
  189. public long BytesTotal // #######################################
  190. {
  191. get { return bytes_total; }
  192. }
  193.  
  194. /// <summary>
  195. /// The size of the file being downloaded/uploaded (Can possibly be 0 if no size is available)
  196. /// </summary>
  197. public long FileSize // #######################################
  198. {
  199. get { return file_size; }
  200. }
  201.  
  202. /// <summary>
  203. /// True: Passive mode [default]
  204. /// False: Active Mode
  205. /// </summary>
  206. public bool PassiveMode // #######################################
  207. {
  208. get { return passive_mode; }
  209. set { passive_mode = value; }
  210. }
  211.  
  212. public bool Noframe {
  213. get { return _noFrame; }
  214. set { _noFrame = value; }
  215. }
  216.  
  217. public void Dispose() {
  218. Disconnect();
  219. }
  220.  
  221. private void Fail() {
  222. Disconnect();
  223. throw new Exception("[ EXCEPTION ] ((FTP)) " + responseStr);
  224. }
  225.  
  226. private void SetBinaryMode(bool mode) {
  227. if (mode)
  228. SendCommand("TYPE I");
  229. else
  230. SendCommand("TYPE A");
  231.  
  232. ReadResponse();
  233. if (response != 200)
  234. Fail();
  235. }
  236.  
  237. private void SendCommand(string command) {
  238. Byte[] cmd = Encoding.ASCII.GetBytes((command + "\r\n").ToCharArray());
  239.  
  240. #if (FTP_DEBUG)
  241. if (command.Length > 3 && command.Substring(0, 4) == "PASS")
  242. Console.WriteLine("\r\n[ DEBUG ] (( FTP )) PASS xxx");
  243. else
  244. Console.WriteLine("\r\n[ DEBUG ] (( FTP )) " + command);
  245. #endif
  246.  
  247. main_sock.Send(cmd, cmd.Length, 0);
  248. }
  249.  
  250. private void FillBucket() {
  251. var bytes = new Byte[512];
  252. long bytesgot;
  253. int msecs_passed = 0; // #######################################
  254.  
  255. while (main_sock.Available < 1) {
  256. Thread.Sleep(50);
  257. msecs_passed += 50;
  258. if (msecs_passed%1000 == 0)
  259. Console.WriteLine("[ INFO ] (( FTP )) Filling bucket..." + msecs_passed);
  260. // this code is just a fail safe option
  261. // so the code doesn't hang if there is
  262. // no data comming.
  263. if (msecs_passed > timeout) {
  264. Disconnect();
  265. throw new Exception("[ EXCEPTION ] ((FTP)) [FillBucket] Timed out while waiting for server response.");
  266. }
  267. }
  268.  
  269. while (main_sock.Available > 0) {
  270. bytesgot = main_sock.Receive(bytes, 512, 0);
  271. bucket += Encoding.ASCII.GetString(bytes, 0, (int)bytesgot);
  272. // this may not be needed, gives any more data that hasn't arrived
  273. // just yet a small chance to get there.
  274. Thread.Sleep(50);
  275. }
  276. }
  277.  
  278. private string GetLineFromBucket() {
  279. int i;
  280. string buf = "";
  281.  
  282. if ((i = bucket.IndexOf('\n')) < 0) {
  283. while (i < 0) {
  284. FillBucket();
  285. i = bucket.IndexOf('\n');
  286. }
  287. }
  288.  
  289. buf = bucket.Substring(0, i);
  290. bucket = bucket.Substring(i + 1);
  291.  
  292. return buf;
  293. }
  294.  
  295. // Any time a command is sent, use ReadResponse() to get the response
  296. // from the server. The variable responseStr holds the entire string and
  297. // the variable response holds the response number.
  298. private void ReadResponse() {
  299. string buf;
  300. messages = String.Empty;
  301.  
  302. while (true) {
  303. //buf = GetLineFromBucket();
  304. buf = GetLineFromBucket();
  305.  
  306. #if (FTP_DEBUG)
  307. Console.WriteLine(buf);
  308. #endif
  309. // the server will respond with "000-Foo bar" on multi line responses
  310. // "000 Foo bar" would be the last line it sent for that response.
  311. // Better example:
  312. // "000-This is a multiline response"
  313. // "000-Foo bar"
  314. // "000 This is the end of the response"
  315. if (Regex.Match(buf, "^[0-9]+ ").Success) {
  316. responseStr = buf;
  317. response = int.Parse(buf.Substring(0, 3));
  318. break;
  319. }
  320. messages += Regex.Replace(buf, "^[0-9]+-", "") + "\n";
  321. }
  322. }
  323.  
  324. // if you add code that needs a data socket, i.e. a PASV or PORT command required,
  325. // call this function to do the dirty work. It sends the PASV or PORT command,
  326. // parses out the port and ip info and opens the appropriate data socket
  327. // for you. The socket variable is private Socket data_socket. Once you
  328. // are done with it, be sure to call CloseDataSocket()
  329. private void OpenDataSocket() {
  330. if (passive_mode) // #######################################
  331. {
  332. string[] pasv;
  333. string server;
  334. int port;
  335.  
  336. Connect();
  337. SendCommand("PASV");
  338. ReadResponse();
  339. if (response != 227)
  340. Fail();
  341.  
  342. try {
  343. int i1, i2;
  344.  
  345. i1 = responseStr.IndexOf('(') + 1;
  346. i2 = responseStr.IndexOf(')') - i1;
  347. pasv = responseStr.Substring(i1, i2).Split(',');
  348. }
  349. catch (Exception ex) {
  350. Disconnect();
  351. throw new Exception("[ EXCEPTION ] ((FTP)) Malformed PASV response: " + responseStr, ex);
  352. }
  353.  
  354. if (pasv.Length < 6) {
  355. Disconnect();
  356. throw new Exception("[ EXCEPTION ] ((FTP)) Malformed PASV response: " + responseStr);
  357. }
  358.  
  359. server = String.Format("{0}.{1}.{2}.{3}", pasv[0], pasv[1], pasv[2], pasv[3]);
  360. port = (int.Parse(pasv[4]) << 8) + int.Parse(pasv[5]);
  361.  
  362. try {
  363. #if (FTP_DEBUG)
  364. Console.WriteLine("[ DEBUG ] (( FTP )) Data socket: {0}:{1}", server, port);
  365. #endif
  366. CloseDataSocket();
  367.  
  368. #if (FTP_DEBUG)
  369. Console.WriteLine("[ DEBUG ] (( FTP )) Creating socket...");
  370. #endif
  371. data_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  372.  
  373. #if (FTP_DEBUG)
  374. Console.WriteLine("[ DEBUG ] (( FTP )) Resolving host");
  375. #endif
  376.  
  377. data_ipEndPoint = new IPEndPoint(GetIP(server), port);
  378.  
  379. #if (FTP_DEBUG)
  380. Console.WriteLine("[ DEBUG ] (( FTP )) Connecting...");
  381. #endif
  382. data_sock.Connect(data_ipEndPoint);
  383.  
  384. #if (FTP_DEBUG)
  385. Console.WriteLine("[ DEBUG ] (( FTP )) Connected.");
  386. #endif
  387. }
  388. catch (Exception ex) {
  389. throw new Exception("[ EXCEPTION ] ((FTP)) Failed to connect for data transfer: " + ex.Message, ex);
  390. }
  391. }
  392. else // #######################################
  393. {
  394. Connect();
  395.  
  396. try {
  397. #if (FTP_DEBUG)
  398. Console.WriteLine("[ DEBUG ] (( FTP )) Data socket (active mode)");
  399. #endif
  400. CloseDataSocket();
  401.  
  402. #if (FTP_DEBUG)
  403. Console.WriteLine("[ DEBUG ] (( FTP )) Creating listening socket...");
  404. #endif
  405. listening_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  406.  
  407. #if (FTP_DEBUG)
  408. Console.WriteLine("[ DEBUG ] (( FTP )) Binding socket to local address/port...");
  409. #endif
  410. // for the PORT command we need to send our IP address; let's extract it
  411. // from the LocalEndPoint of the main socket, that's already connected
  412. string sLocAddr = main_sock.LocalEndPoint.ToString();
  413. int ix = sLocAddr.IndexOf(':');
  414. if (ix < 0)
  415. throw new Exception("[ EXCEPTION ] ((FTP)) Failed to parse local address <" + sLocAddr + ">");
  416. string sIPAddr = sLocAddr.Substring(0, ix);
  417. // let the system automatically assign a port number (setting port = 0)
  418. var localEP = new IPEndPoint(IPAddress.Parse(sIPAddr), 0);
  419.  
  420. listening_sock.Bind(localEP);
  421. sLocAddr = listening_sock.LocalEndPoint.ToString();
  422. ix = sLocAddr.IndexOf(':');
  423. if (ix < 0)
  424. throw new Exception("[ EXCEPTION ] ((FTP)) Failed to parse the local address <" + sLocAddr + ">");
  425. int nPort = int.Parse(sLocAddr.Substring(ix + 1));
  426. #if (FTP_DEBUG)
  427. Console.WriteLine("[ DEBUG ] (( FTP )) Listening on {0}:{1}", sIPAddr, nPort);
  428. #endif
  429. // start to listen for a connection request from the host (note that
  430. // Listen is not blocking) and send the PORT command
  431. listening_sock.Listen(1);
  432. string sPortCmd = string.Format("PORT {0},{1},{2}", sIPAddr.Replace('.', ','), nPort/256, nPort%256);
  433. SendCommand(sPortCmd);
  434. ReadResponse();
  435. if (response != 200)
  436. Fail();
  437. }
  438. catch (Exception ex) {
  439. throw new Exception("[ EXCEPTION ] ((FTP)) Failed to connect for data transfer: " + ex.Message, ex.InnerException);
  440. }
  441. }
  442. }
  443.  
  444. private void ConnectDataSocket() // #######################################
  445. {
  446. if (data_sock != null) // already connected (always so if passive mode)
  447. return;
  448.  
  449. try {
  450. #if (FTP_DEBUG)
  451. Console.WriteLine("[ DEBUG ] (( FTP )) Accepting connections...");
  452. #endif
  453. data_sock = listening_sock.Accept(); // Accept is blocking
  454. listening_sock.Close();
  455. listening_sock = null;
  456.  
  457. if (data_sock == null)
  458. throw new Exception("[ EXCEPTION ] ((FTP)) Winsock error: " + Convert.ToString(Marshal.GetLastWin32Error()));
  459. #if (FTP_DEBUG)
  460. Console.WriteLine("[ DEBUG ] (( FTP )) Connected.");
  461. #endif
  462. }
  463. catch (Exception ex) {
  464. throw new Exception("[ EXCEPTION ] ((FTP)) Failed to connect: " + ex.Message, ex.InnerException);
  465. }
  466. }
  467.  
  468. private void CloseDataSocket() {
  469. #if (FTP_DEBUG)
  470. Console.WriteLine("[ DEBUG ] (( FTP )) Attempting to close data channel socket...");
  471. #endif
  472. if (data_sock != null) {
  473. if (data_sock.Connected) {
  474. #if (FTP_DEBUG)
  475. Console.WriteLine("[ DEBUG ] (( FTP )) Closing data channel socket!");
  476. #endif
  477. data_sock.Close();
  478. #if (FTP_DEBUG)
  479. Console.WriteLine("[ DEBUG ] (( FTP )) Data channel socket closed!");
  480. #endif
  481. }
  482. data_sock = null;
  483. }
  484.  
  485. data_ipEndPoint = null;
  486. }
  487.  
  488. /// <summary>
  489. /// Closes all connections to the ftp server
  490. /// </summary>
  491. public void Disconnect() {
  492. CloseDataSocket();
  493.  
  494. if (main_sock != null) {
  495. if (main_sock.Connected) {
  496. SendCommand("QUIT");
  497. main_sock.Close();
  498. }
  499. main_sock = null;
  500. }
  501.  
  502. if (file != null)
  503. file.Close();
  504.  
  505. main_ipEndPoint = null;
  506. file = null;
  507. }
  508.  
  509. /// <summary>
  510. /// Connect to a ftp server
  511. /// </summary>
  512. /// <param name="server">IP or hostname of the server to connect to</param>
  513. /// <param name="port">Port number the server is listening on</param>
  514. /// <param name="user">Account name to login as</param>
  515. /// <param name="pass">Password for the account specified</param>
  516. public void Connect(string server, int port, string user, string pass) {
  517. this.server = server;
  518. this.user = user;
  519. this.pass = pass;
  520. this.port = port;
  521.  
  522. Connect();
  523. }
  524.  
  525. /// <summary>
  526. /// Connect to a ftp server
  527. /// </summary>
  528. /// <param name="server">IP or hostname of the server to connect to</param>
  529. /// <param name="user">Account name to login as</param>
  530. /// <param name="pass">Password for the account specified</param>
  531. public void Connect(string server, string user, string pass) {
  532. this.server = server;
  533. this.user = user;
  534. this.pass = pass;
  535.  
  536. Connect();
  537. }
  538.  
  539. /// <summary>
  540. /// Connect to an ftp server
  541. /// </summary>
  542. public void Connect() {
  543. if (server == null || server.Trim() == String.Empty)
  544. throw new Exception("[ EXCEPTION ] ((FTP)) [Connect] No server has been set.");
  545. if (user == null || user.Trim() == String.Empty)
  546. throw new Exception("[ EXCEPTION ] ((FTP)) [Connect] No username has been set.");
  547.  
  548. if (main_sock != null) {
  549. if (main_sock.Connected)
  550. return;
  551. }
  552.  
  553. // GetHostEntry liefert (bei Handy) eine andere IP zurück, als mit "server" übermittelt wird: WTF
  554. //var address_list = Dns.GetHostEntry(server).AddressList;
  555.  
  556. try {
  557. main_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  558. main_ipEndPoint = new IPEndPoint(GetIP(server), port);
  559. main_sock.Connect(main_ipEndPoint);
  560. }
  561. catch (Exception ex) {
  562. throw new Exception("[ EXCEPTION ] ((FTP)) [Connect] Server: " + server + " (Address: " + GetIP(server) + " )\n" + ex.Message, ex);
  563. }
  564.  
  565. ReadResponse();
  566. if (response != 220)
  567. Fail();
  568.  
  569. SendCommand("USER " + user);
  570. ReadResponse();
  571.  
  572. switch (response) {
  573. case 331:
  574. if (pass == null) {
  575. Disconnect();
  576. throw new Exception("[ EXCEPTION ] ((FTP)) [Connect] No password has been set.");
  577. }
  578. SendCommand("PASS " + pass);
  579. ReadResponse();
  580. if (response != 230)
  581. Fail();
  582. break;
  583. case 230:
  584. break;
  585. }
  586. }
  587.  
  588. /// <summary>
  589. /// Retrieves a list of files from the ftp server
  590. /// </summary>
  591. /// <returns>An ArrayList of files</returns>
  592. public ArrayList List(bool justFileNames = false) {
  593. var bytes = new Byte[512];
  594. string file_list = "";
  595. long bytesgot = 0;
  596. int msecs_passed = 0;
  597. var list = new ArrayList();
  598.  
  599. Connect();
  600. OpenDataSocket();
  601. if (justFileNames)
  602. SendCommand("NLST");
  603. else
  604. SendCommand("LIST");
  605. ReadResponse();
  606.  
  607. //FILIPE MADUREIRA.
  608. //Added response 125
  609. switch (response) {
  610. case 125:
  611. case 150:
  612. break;
  613. default:
  614. CloseDataSocket();
  615. throw new Exception("[ EXCEPTION ] ((FTP)) [List] " + responseStr);
  616. }
  617. ConnectDataSocket(); // #######################################
  618.  
  619. while (data_sock.Available < 1) {
  620. Thread.Sleep(50);
  621. msecs_passed += 50;
  622. // this code is just a fail safe option
  623. // so the code doesn't hang if there is
  624. // no data comming.
  625. if (msecs_passed > (timeout/10)) {
  626. //CloseDataSocket();
  627. //throw new Exception("[ EXCEPTION ] ((FTP)) Timed out waiting on server to respond.");
  628.  
  629. //FILIPE MADUREIRA.
  630. //If there are no files to list it gives timeout.
  631. //So I wait less time and if no data is received, means that there are no files
  632. break; //Maybe there are no files
  633. }
  634. }
  635.  
  636. while (data_sock.Available > 0) {
  637. bytesgot = data_sock.Receive(bytes, bytes.Length, 0);
  638. file_list += Encoding.ASCII.GetString(bytes, 0, (int)bytesgot);
  639. // *23.01.2012 martin Anpassung von 50 auf 500 da es bei GANTNER-Terminals zu Datenberludeten kam bei der Abfrage!!
  640. Thread.Sleep(500); // *shrug*, sometimes there is data comming but it isn't there yet.
  641. }
  642.  
  643. CloseDataSocket();
  644.  
  645. ReadResponse();
  646. if (response != 226)
  647. throw new Exception("[ EXCEPTION ] ((FTP)) [List] " + responseStr);
  648.  
  649. foreach (string f in file_list.Split('\n')) {
  650. if (f.Length > 0 && !Regex.Match(f, "^total").Success)
  651. list.Add(f.Substring(0, f.Length - 1));
  652. }
  653.  
  654. return list;
  655. }
  656.  
  657. /// <summary>
  658. /// Gets a file list only
  659. /// </summary>
  660. /// <returns>ArrayList of files only</returns>
  661. public ArrayList ListFiles() {
  662. var list = new ArrayList();
  663.  
  664. foreach (string f in List()) {
  665. //FILIPE MADUREIRA
  666. //In Windows servers it is identified by <DIR>
  667. if ((f.Length > 0)) {
  668. if ((f[0] != 'd') && (f.ToUpper().IndexOf("<DIR>") < 0))
  669. list.Add(f);
  670. }
  671. }
  672.  
  673. return list;
  674. }
  675.  
  676. public List<string> ListFileNamesOnly(string searchString = "") {
  677. var list = new List<string>();
  678.  
  679. foreach (string f in List(true)) //List(true) only retrieves names
  680. {
  681. if (searchString.Length == 0 || f.Contains(searchString))
  682. list.Add(f);
  683. }
  684.  
  685. return list;
  686. }
  687.  
  688. /// <summary>
  689. /// Gets a directory list only
  690. /// </summary>
  691. /// <returns>ArrayList of directories only</returns>
  692. public ArrayList ListDirectories() {
  693. var list = new ArrayList();
  694.  
  695. foreach (string f in List()) {
  696. //FILIPE MADUREIRA
  697. //In Windows servers it is identified by <DIR>
  698. if (f.Length > 0) {
  699. if ((f[0] == 'd') || (f.ToUpper().IndexOf("<DIR>") >= 0))
  700. list.Add(f);
  701. }
  702. }
  703.  
  704. return list;
  705. }
  706.  
  707. /// <summary>
  708. /// Returns the 'Raw' DateInformation in ftp format. (YYYYMMDDhhmmss). Use GetFileDate to return a DateTime object as a
  709. /// better option.
  710. /// </summary>
  711. /// <param name="fileName">Remote FileName to Query</param>
  712. /// <returns>Returns the 'Raw' DateInformation in ftp format</returns>
  713. public string GetFileDateRaw(string fileName) {
  714. Connect();
  715.  
  716. SendCommand("MDTM " + fileName);
  717. ReadResponse();
  718. if (response != 213) {
  719. #if (FTP_DEBUG)
  720. Console.WriteLine("\r\n[ DEBUG ] (( FTP )) [GetFileDateRaw] " + responseStr);
  721. #endif
  722. throw new Exception("[ EXCEPTION ] ((FTP)) [GetFileDateRaw] " + responseStr);
  723. }
  724.  
  725. return (responseStr.Substring(4));
  726. }
  727.  
  728. /// <summary>
  729. /// GetFileDate will query the ftp server for the date of the remote file.
  730. /// </summary>
  731. /// <param name="fileName">Remote FileName to Query</param>
  732. /// <returns>DateTime of the Input FileName</returns>
  733. public DateTime GetFileDate(string fileName) {
  734. return ConvertFTPDateToDateTime(GetFileDateRaw(fileName));
  735. }
  736.  
  737. private DateTime ConvertFTPDateToDateTime(string input) {
  738. if (input.Length < 14)
  739. throw new ArgumentException("[ EXCEPTION ] ((FTP)) [ConvertFTPDateToDateTime] Input Value for method was too short.");
  740.  
  741. //YYYYMMDDhhmmss":
  742. int year = Convert.ToInt16(input.Substring(0, 4));
  743. int month = Convert.ToInt16(input.Substring(4, 2));
  744. int day = Convert.ToInt16(input.Substring(6, 2));
  745. int hour = Convert.ToInt16(input.Substring(8, 2));
  746. int min = Convert.ToInt16(input.Substring(10, 2));
  747. int sec = Convert.ToInt16(input.Substring(12, 2));
  748.  
  749. return new DateTime(year, month, day, hour, min, sec);
  750. }
  751.  
  752. /// <summary>
  753. /// Get the working directory on the ftp server
  754. /// </summary>
  755. /// <returns>The working directory</returns>
  756. public string GetWorkingDirectory() {
  757. //PWD - print working directory
  758. Connect();
  759. SendCommand("PWD");
  760. ReadResponse();
  761.  
  762. if (response != 257)
  763. throw new Exception("[ EXCEPTION ] ((FTP)) [GetWorkingDirectory]" + responseStr);
  764.  
  765. string pwd;
  766. try {
  767. pwd = responseStr.Substring(responseStr.IndexOf("\"", 0) + 1); //5);
  768. pwd = pwd.Substring(0, pwd.LastIndexOf("\""));
  769. pwd = pwd.Replace("\"\"", "\""); // directories with quotes in the name come out as "" from the server
  770. }
  771. catch (Exception ex) {
  772. throw new Exception("[ EXCEPTION ] ((FTP)) [GetWorkingDirectory] " + ex.Message);
  773. }
  774.  
  775. return pwd;
  776. }
  777.  
  778. /// <summary>
  779. /// Change to another directory on the ftp server
  780. /// </summary>
  781. /// <param name="path">Directory to change to</param>
  782. public void ChangeDir(string path) {
  783. Connect();
  784. SendCommand("CWD " + path);
  785. ReadResponse();
  786. if (response != 250) {
  787. #if (FTP_DEBUG)
  788. Console.WriteLine("\r\n[ DEBUG ] ((FTP)) [ChangeDir] " + responseStr);
  789. #endif
  790. throw new Exception("[ EXCEPTION ] ((FTP)) [ChangeDir] " + responseStr);
  791. }
  792. }
  793.  
  794. /// <summary>
  795. /// Create a directory on the ftp server
  796. /// </summary>
  797. /// <param name="dir">Directory to create</param>
  798. public void MakeDir(string dir) {
  799. Connect();
  800. SendCommand("MKD " + dir);
  801. ReadResponse();
  802.  
  803. switch (response) {
  804. case 257:
  805. case 250:
  806. break;
  807. default:
  808. #if (FTP_DEBUG)
  809. Console.WriteLine("\r\n[ DEBUG ] ((FTP)) [MakeDir] " + responseStr);
  810. #endif
  811. throw new Exception("[ EXCEPTION ] ((FTP)) [MakeDir] " + responseStr);
  812. }
  813. }
  814.  
  815. /// <summary>
  816. /// Remove a directory from the ftp server
  817. /// </summary>
  818. /// <param name="dir">Name of directory to remove</param>
  819. public void RemoveDir(string dir) {
  820. Connect();
  821. SendCommand("RMD " + dir);
  822. ReadResponse();
  823. if (response != 250) {
  824. #if (FTP_DEBUG)
  825. Console.WriteLine("\r\n[ DEBUG ] ((FTP)) [RemoveDir] " + responseStr);
  826. #endif
  827. throw new Exception("[ EXCEPTION ] ((FTP)) [RemoveDir] " + responseStr);
  828. }
  829. }
  830.  
  831. /// <summary>
  832. /// Remove a file from the ftp server
  833. /// </summary>
  834. /// <param name="filename">Name of the file to delete</param>
  835. public void RemoveFile(string filename) {
  836. Connect();
  837. SendCommand("DELE " + filename);
  838. ReadResponse();
  839. if (response != 250) {
  840. #if (FTP_DEBUG)
  841. Console.WriteLine("\r\n[ DEBUG ] ((FTP)) SendCommand DELE: " + responseStr);
  842. #endif
  843. throw new Exception("[ EXCEPTION ] ((FTP)) SendCommand DELE: " + responseStr);
  844. }
  845. }
  846.  
  847. /// <summary>
  848. /// Rename a file on the ftp server
  849. /// </summary>
  850. /// <param name="oldfilename">Old file name</param>
  851. /// <param name="newfilename">New file name</param>
  852. public void RenameFile(string oldfilename, string newfilename) // #######################################
  853. {
  854. Connect();
  855. SendCommand("RNFR " + oldfilename);
  856. ReadResponse();
  857. if (response != 350) {
  858. #if (FTP_DEBUG)
  859. Console.WriteLine("\r\n[ DEBUG ] ((FTP)) SendCommand RNFR: " + responseStr);
  860. #endif
  861. throw new Exception("[ EXCEPTION ] ((FTP)) SendCommand RNFR: " + responseStr);
  862. }
  863. SendCommand("RNTO " + newfilename);
  864. ReadResponse();
  865. if (response != 250) {
  866. #if (FTP_DEBUG)
  867. Console.WriteLine("\r\n[ DEBUG ] ((FTP)) SendCommand RNTO: " + responseStr);
  868. #endif
  869. throw new Exception("[ EXCEPTION ] ((FTP)) SendCommand RNTO: " + responseStr);
  870. }
  871. }
  872.  
  873. /// <summary>
  874. /// Get the size of a file (Provided the ftp server supports it)
  875. /// </summary>
  876. /// <param name="filename">Name of file</param>
  877. /// <returns>The size of the file specified by filename</returns>
  878. public long GetFileSize(string filename) {
  879. Connect();
  880. SendCommand("SIZE " + filename);
  881. ReadResponse();
  882. if (response != 213) {
  883. #if (FTP_DEBUG)
  884. Console.WriteLine("\r\n[ DEBUG ] ((FTP)) [GetFileSize] " + responseStr);
  885. #endif
  886. throw new Exception("[ EXCEPTION ] ((FTP)) [GetFileSize] " + responseStr);
  887. }
  888.  
  889. return Int64.Parse(responseStr.Substring(4));
  890. }
  891.  
  892. /// <summary>
  893. /// Open an upload with no resume if it already exists
  894. /// </summary>
  895. /// <param name="filename">File to upload</param>
  896. public void OpenUpload(string filename) {
  897. OpenUpload(filename, filename, false);
  898. }
  899.  
  900. /// <summary>
  901. /// Open an upload with no resume if it already exists
  902. /// </summary>
  903. /// <param name="filename">Local file to upload (Can include path to file)</param>
  904. /// <param name="remotefilename">Filename to store file as on ftp server</param>
  905. public void OpenUpload(string filename, string remotefilename) {
  906. OpenUpload(filename, remotefilename, false);
  907. }
  908.  
  909. /// <summary>
  910. /// Open an upload with resume support
  911. /// </summary>
  912. /// <param name="filename">Local file to upload (Can include path to file)</param>
  913. /// <param name="resume">Attempt resume if exists</param>
  914. public void OpenUpload(string filename, bool resume) {
  915. OpenUpload(filename, filename, resume);
  916. }
  917.  
  918. /// <summary>
  919. /// Open an upload with resume support
  920. /// </summary>
  921. /// <param name="filename">Local file to upload (Can include path to file)</param>
  922. /// <param name="remote_filename">Filename to store file as on ftp server</param>
  923. /// <param name="resume">Attempt resume if exists</param>
  924. public void OpenUpload(string filename, string remote_filename, bool resume) {
  925. Connect();
  926. SetBinaryMode(true);
  927. OpenDataSocket();
  928.  
  929. bytes_total = 0;
  930.  
  931. try {
  932. file = new FileStream(filename, FileMode.Open);
  933. }
  934. catch (Exception ex) {
  935. file = null;
  936. throw ex;
  937. }
  938.  
  939. file_size = file.Length;
  940.  
  941. if (resume) {
  942. long size = GetFileSize(remote_filename);
  943. SendCommand("REST " + size);
  944. ReadResponse();
  945. #if FTP_DEBUG
  946. Console.WriteLine("[ DEBUG ] (( FTP )) ReadResponse > " + response);
  947. #endif
  948. if (response == 350)
  949. file.Seek(size, SeekOrigin.Begin);
  950. }
  951.  
  952. SendCommand("STOR " + remote_filename);
  953. ReadResponse();
  954. #if FTP_DEBUG
  955. Console.WriteLine("[ DEBUG ] (( FTP )) ReadResponse > " + response);
  956. #endif
  957. switch (response) {
  958. case 125:
  959. case 150:
  960. break;
  961. default:
  962. file.Close();
  963. file = null;
  964. throw new Exception("[ EXCEPTION ] ((FTP)) [OpenUpload] " + responseStr);
  965. }
  966. ConnectDataSocket(); // #######################################
  967. }
  968.  
  969. /// <summary>
  970. /// Download a file with no resume
  971. /// </summary>
  972. /// <param name="filename">Remote file name</param>
  973. public void OpenDownload(string filename) {
  974. OpenDownload(filename, filename, false);
  975. }
  976.  
  977. /// <summary>
  978. /// Download a file with optional resume
  979. /// </summary>
  980. /// <param name="filename">Remote file name</param>
  981. /// <param name="resume">Attempt resume if file exists</param>
  982. public void OpenDownload(string filename, bool resume) {
  983. OpenDownload(filename, filename, resume);
  984. }
  985.  
  986. /// <summary>
  987. /// Download a file with no attempt to resume
  988. /// </summary>
  989. /// <param name="filename">Remote filename</param>
  990. /// <param name="localfilename">Local filename (Can include path to file)</param>
  991. public void OpenDownload(string filename, string localfilename) {
  992. OpenDownload(filename, localfilename, false);
  993. }
  994.  
  995. /// <summary>
  996. /// Open a file for download
  997. /// </summary>
  998. /// <param name="remote_filename">The name of the file on the FTP server</param>
  999. /// <param name="local_filename">The name of the file to save as (Can include path to file)</param>
  1000. /// <param name="resume">Attempt resume if file exists</param>
  1001. public void OpenDownload(string remote_filename, string local_filename, bool resume) {
  1002. Connect();
  1003. SetBinaryMode(true);
  1004.  
  1005. bytes_total = 0;
  1006.  
  1007. try {
  1008. file_size = GetFileSize(remote_filename);
  1009. }
  1010. catch {
  1011. file_size = 0;
  1012. }
  1013.  
  1014. if (resume && File.Exists(local_filename)) {
  1015. try {
  1016. file = new FileStream(local_filename, FileMode.Open);
  1017. }
  1018. catch (Exception ex) {
  1019. file = null;
  1020. throw ex;
  1021. }
  1022.  
  1023. SendCommand("REST " + file.Length);
  1024. ReadResponse();
  1025. if (response != 350)
  1026. throw new Exception("[ EXCEPTION ] ((FTP)) [OpenDownload] " + responseStr);
  1027. file.Seek(file.Length, SeekOrigin.Begin);
  1028. bytes_total = file.Length;
  1029. }
  1030. else {
  1031. try {
  1032. file = new FileStream(local_filename, FileMode.Create);
  1033. }
  1034. catch (Exception ex) {
  1035. file = null;
  1036. throw ex;
  1037. }
  1038. }
  1039.  
  1040. OpenDataSocket();
  1041. SendCommand("RETR " + remote_filename);
  1042. ReadResponse();
  1043.  
  1044. switch (response) {
  1045. case 125:
  1046. case 150:
  1047. break;
  1048. default:
  1049. file.Close();
  1050. file = null;
  1051. throw new Exception("[ EXCEPTION ] ((FTP)) [OpenDownload] " + responseStr);
  1052. }
  1053. ConnectDataSocket();
  1054. }
  1055.  
  1056. /// <summary>
  1057. /// Upload the file, to be used in a loop until file is completely uploaded
  1058. /// </summary>
  1059. /// <returns>Bytes sent</returns>
  1060. public long DoUpload() {
  1061. try {
  1062. var bytes = new Byte[512];
  1063. long bytes_got = file.Read(bytes, 0, bytes.Length);
  1064. bytes_total += bytes_got;
  1065. data_sock.Send(bytes, (int)bytes_got, 0);
  1066. packages_sent++;
  1067.  
  1068. // console output of current transfer
  1069. timeTaken = DateTime.Now - tailtime;
  1070. if (bytes_got < 512 || timeTaken.TotalSeconds > 3) {
  1071. if (bytes_got == 0)
  1072. kbPerSec = 0;
  1073. else if (bytes_got == bytes_total)
  1074. kbPerSec = (int)(bytes_total/1024);
  1075. else
  1076. kbPerSec = (int)(((bytes_total - bytes_tail)/1024)/timeTaken.TotalSeconds);
  1077. Console.WriteLine(packages_sent + " > bytes_got: " + bytes_got + " bytes_total: " + bytes_total + " kbPerSec: " + kbPerSec);
  1078. tailtime = DateTime.Now;
  1079. bytes_tail = bytes_total;
  1080. }
  1081.  
  1082. if (bytes_got <= 0) {
  1083. // the upload is complete or an error occured
  1084. file.Close();
  1085. file = null;
  1086.  
  1087. CloseDataSocket();
  1088. ReadResponse();
  1089. switch (response) {
  1090. case 226:
  1091. case 250:
  1092. break;
  1093. default:
  1094. throw new Exception(responseStr);
  1095. }
  1096.  
  1097. SetBinaryMode(false);
  1098. }
  1099. return bytes_got;
  1100. }
  1101. catch (Exception ex) {
  1102. #if FTP_DEBUG
  1103. Console.WriteLine("[ EXCEPTION ] (( FTP )) [DoUpload] " + ex.Message);
  1104. Console.WriteLine("[ EXCEPTION - ST ] (( FTP )) [DoUpload] " + ex.StackTrace);
  1105. #endif
  1106. if (file != null) {
  1107. file.Close();
  1108. file = null;
  1109. }
  1110.  
  1111. CloseDataSocket();
  1112. SetBinaryMode(false);
  1113. throw;
  1114. }
  1115. }
  1116.  
  1117. /// <summary>
  1118. /// Download a file, to be used in a loop until the file is completely downloaded
  1119. /// </summary>
  1120. /// <returns>Number of bytes recieved</returns>
  1121. public long DoDownload() {
  1122. try {
  1123. var bytes = new Byte[512];
  1124. long bytes_got = data_sock.Receive(bytes, bytes.Length, 0);
  1125.  
  1126. if (bytes_got <= 0) {
  1127. file.Close();
  1128. file = null;
  1129.  
  1130. // the download is done or an error occured
  1131. CloseDataSocket();
  1132. ReadResponse();
  1133.  
  1134. switch (response) {
  1135. case 226:
  1136. case 250:
  1137. break;
  1138. default:
  1139. throw new Exception(responseStr);
  1140. }
  1141.  
  1142. SetBinaryMode(false);
  1143.  
  1144. return bytes_got;
  1145. }
  1146.  
  1147. file.Write(bytes, 0, (int)bytes_got);
  1148. bytes_total += bytes_got;
  1149.  
  1150. return bytes_got;
  1151. }
  1152. catch (Exception ex) {
  1153. #if FTP_DEBUG
  1154. Console.WriteLine("[ EXCEPTION ] (( FTP )) [DoDownload]: " + ex.Message);
  1155. Console.WriteLine("[ EXCEPTION - ST ] (( FTP )) [DoDownload]: " + ex.StackTrace);
  1156. #endif
  1157. if (file != null) {
  1158. file.Close();
  1159. file = null;
  1160. }
  1161.  
  1162. CloseDataSocket();
  1163. SetBinaryMode(false);
  1164. throw ex;
  1165. }
  1166. }
  1167.  
  1168. /// <summary>
  1169. /// sets connection timeout
  1170. /// </summary>
  1171. /// <param name="timeout">timeout in seconds</param>
  1172. public void setTimeout(int timeout) {
  1173. this.timeout = timeout*1000;
  1174. }
  1175.  
  1176. /// <summary>
  1177. /// if true no
  1178. /// </summary>
  1179. /// <param name="noFrame"></param>
  1180. [Obsolete("Use setter Noframe instead.")]
  1181. public void NoFrame(bool noFrame) {
  1182. _noFrame = noFrame;
  1183. }
  1184.  
  1185. public IPAddress GetIP(string s_address) {
  1186. IPAddress ipAddress;
  1187. if (IPAddress.TryParse(s_address, out ipAddress))
  1188. return ipAddress;
  1189.  
  1190. foreach (var addr in Dns.GetHostEntry(s_address).AddressList) {
  1191. if (addr.AddressFamily == AddressFamily.InterNetwork)
  1192. return addr;
  1193. }
  1194.  
  1195. throw new Exception("Unable to parse provided string");
  1196. }
  1197.  
  1198. #region Von Waldo hinzugefügt
  1199. /// <summary>
  1200. /// </summary>
  1201. /// <param name="FileName"></param>
  1202. /// <returns></returns>
  1203. public bool Upload(string FileName) {
  1204. return Upload(FileName, FileName);
  1205. }
  1206.  
  1207. /// <summary>
  1208. /// wrapper, download with or without displaying a progress frame.
  1209. /// </summary>
  1210. /// <param name="FileName"></param>
  1211. /// <param name="RemoteFileName"></param>
  1212. /// <returns></returns>
  1213. public bool Upload(string FileName, string RemoteFileName) {
  1214. if (_noFrame)
  1215. return UploadNoFrame(FileName, RemoteFileName);
  1216. return UploadWithFrame(FileName, RemoteFileName);
  1217. }
  1218.  
  1219. /// <summary>
  1220. /// </summary>
  1221. /// <param name="FileName"></param>
  1222. /// <param name="RemoteFileName"></param>
  1223. /// <returns></returns>
  1224. public bool UploadWithFrame(string FileName, string RemoteFileName) {
  1225. var frm = new Form_Wait();
  1226.  
  1227. try {
  1228. frm.Info = "Uploading " + FileName + "...";
  1229. frm.ShowFortschritt = false;
  1230. frm.Show();
  1231. frm.Refresh();
  1232.  
  1233. OpenUpload(FileName, RemoteFileName, false);
  1234.  
  1235. frm.initProgress(0, Convert.ToInt32(FileSize/10000));
  1236. frm.ShowFortschritt = true;
  1237. frm.Refresh();
  1238.  
  1239. tailtime = DateTime.Now;
  1240. packages_sent = 0;
  1241.  
  1242. while (file != null && DoUpload() > 0) {
  1243. if (BytesTotal%100 == 0) {
  1244. frm.Value = Convert.ToInt32(BytesTotal/10000);
  1245. frm.Refresh();
  1246. }
  1247. }
  1248. frm.Info = "Upload done.";
  1249. return true;
  1250. }
  1251. catch (Exception ex) {
  1252. #if FTP_DEBUG
  1253. Console.WriteLine("[ EXCEPTION ] (( FTP )) [DoUploadWithFrame]: " + ex.Message);
  1254. Console.WriteLine("[ EXCEPTION - ST ] (( FTP )) [DoUploadWithFrame]: " + ex.StackTrace);
  1255. #endif
  1256. throw ex;
  1257. }
  1258. finally {
  1259. frm.Close();
  1260. }
  1261. }
  1262.  
  1263. /// <summary>
  1264. /// </summary>
  1265. /// <param name="FileName"></param>
  1266. /// <param name="RemoteFileName"></param>
  1267. /// <returns></returns>
  1268. public bool UploadNoFrame(string FileName, string RemoteFileName) {
  1269. try {
  1270. #if FTP_DEBUG
  1271. Console.WriteLine("[ DEBUG ] (( FTP )) Uploading " + FileName + "...");
  1272. #endif
  1273.  
  1274. OpenUpload(FileName, RemoteFileName, false);
  1275.  
  1276. tailtime = DateTime.Now;
  1277. packages_sent = 0;
  1278.  
  1279. while (file != null && DoUpload() > 0)
  1280. ;
  1281. #if FTP_DEBUG
  1282. Console.WriteLine("[ DEBUG ] (( FTP )) done.");
  1283. #endif
  1284. return true;
  1285. }
  1286. catch (Exception ex) {
  1287. #if FTP_DEBUG
  1288. Console.WriteLine("[ EXCEPTION ] (( FTP )) [UploadNoFrame]: " + ex.Message);
  1289. Console.WriteLine("[ EXCEPTION - ST ] (( FTP )) [UploadNoFrame]: " + ex.StackTrace);
  1290. #endif
  1291. throw ex;
  1292. }
  1293. }
  1294.  
  1295. /// <summary>
  1296. /// wrapper, download with or without displaying a progress frame.
  1297. /// </summary>
  1298. /// <param name="FileName"></param>
  1299. /// <param name="LocalFileName"></param>
  1300. /// <returns></returns>
  1301. public bool Download(string FileName, string LocalFileName) {
  1302. if (_noFrame)
  1303. return DownloadNoFrame(FileName, LocalFileName);
  1304. return DownloadWithFrame(FileName, LocalFileName);
  1305. }
  1306.  
  1307. /// <summary>
  1308. /// </summary>
  1309. /// <param name="FileName"></param>
  1310. /// <param name="LocalFileName"></param>
  1311. /// <returns></returns>
  1312. public bool DownloadWithFrame(string FileName, string LocalFileName) {
  1313. var frm = new Form_Wait();
  1314.  
  1315. try {
  1316. frm.Info = "Datei " + FileName + " wird heruntergeladen ...";
  1317. frm.ShowFortschritt = false;
  1318. frm.Show();
  1319. frm.Refresh();
  1320.  
  1321. OpenDownload(FileName, LocalFileName, false);
  1322.  
  1323. frm.initProgress(0, Convert.ToInt32(FileSize/10000));
  1324. frm.ShowFortschritt = true;
  1325. frm.Refresh();
  1326.  
  1327. while (DoDownload() > 0) {
  1328. if (BytesTotal%100 == 0) {
  1329. frm.Value = Convert.ToInt32(BytesTotal/10000);
  1330. frm.Refresh();
  1331. }
  1332. }
  1333.  
  1334. return true;
  1335. }
  1336. finally {
  1337. frm.Close();
  1338. }
  1339. }
  1340.  
  1341. /// <summary>
  1342. /// </summary>
  1343. /// <param name="FileName"></param>
  1344. /// <param name="LocalFileName"></param>
  1345. /// <returns></returns>
  1346. public bool DownloadNoFrame(string FileName, string LocalFileName) {
  1347. #if FTP_DEBUG
  1348. Console.WriteLine("[ DEBUG ] (( FTP )) Downloading " + FileName + "...");
  1349. #endif
  1350.  
  1351. OpenDownload(FileName, LocalFileName, false);
  1352.  
  1353. while (DoDownload() > 0)
  1354. ;
  1355. #if FTP_DEBUG
  1356. Console.WriteLine("[ DEBUG ] (( FTP )) done.");
  1357. #endif
  1358. return true;
  1359. }
  1360. #endregion
  1361. }
  1362. }
Add Comment
Please, Sign In to add comment