-
Notifications
You must be signed in to change notification settings - Fork 19
/
ftplib.cs
1282 lines (1163 loc) · 32.5 KB
/
ftplib.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2006, J.P. Trosclair
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and
* the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Based on FTPFactory.cs code, pretty much a complete re-write with FTPFactory.cs
* as a reference.
*
***********************
* Authors of this code:
***********************
* J.P. Trosclair ([email protected])
* Filipe Madureira ([email protected])
* Carlo M. Andreoli ([email protected])
* Sloan Holliday ([email protected])
*
***********************
* FTPFactory.cs was written by Jaimon Mathew ([email protected])
* and modified by Dan Rolander ([email protected]).
* http://www.csharphelp.com/archives/archive9.html
***********************
*
* ** DO NOT ** contact the authors of FTPFactory.cs about problems with this code. It
* is not their responsibility. Only contact people listed as authors of THIS CODE.
*
* Any bug fixes or additions to the code will be properly credited to the author.
*
* BUGS: There probably are plenty. If you fix one, please email me with info
* about the bug and the fix, code is welcome.
*
* All calls to the ftplib functions should be:
*
* try
* {
* // ftplib function call
* }
* catch(Exception ex)
* {
* // error handeler
* }
*
* If you add to the code please make use of OpenDataSocket(), CloseDataSocket(), and
* ReadResponse() appropriately. See the comments above each for info about using them.
*
* The Fail() function terminates the entire connection. Only call it on critical errors.
* Non critical errors should NOT close the connection.
* All errors should throw an exception of type Exception with the response string from
* the server as the message.
*
* See the simple ftp client for examples on using this class
*/
//#define FTP_DEBUG
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
namespace FTPLib
{
public class FTP
{
#region Public Variables
/// <summary>
/// IP address or hostname to connect to
/// </summary>
public string server;
/// <summary>
/// Username to login as
/// </summary>
public string user;
/// <summary>
/// Password for account
/// </summary>
public string pass;
/// <summary>
/// Port number the FTP server is listening on
/// </summary>
public int port;
/// <summary>
/// The timeout (miliseconds) for waiting on data to arrive
/// </summary>
public int timeout;
#endregion
#region Private Variables
private string messages; // server messages
private string responseStr; // server response if the user wants it.
private bool passive_mode; // #######################################
private long bytes_total; // upload/download info if the user wants it.
private long file_size; // gets set when an upload or download takes place
private Socket main_sock;
private IPEndPoint main_ipEndPoint;
private Socket listening_sock;
private Socket data_sock;
private IPEndPoint data_ipEndPoint;
private FileStream file;
private int response;
private string bucket;
#endregion
#region Constructors
/// <summary>
/// Constructor
/// </summary>
public FTP()
{
server = null;
user = null;
pass = null;
port = 21;
passive_mode = true; // #######################################
main_sock = null;
main_ipEndPoint = null;
listening_sock = null;
data_sock = null;
data_ipEndPoint = null;
file = null;
bucket = "";
bytes_total = 0;
timeout = 10000; // 10 seconds
messages = "";
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="server">Server to connect to</param>
/// <param name="user">Account to login as</param>
/// <param name="pass">Account password</param>
public FTP(string server, string user, string pass)
{
this.server = server;
this.user = user;
this.pass = pass;
port = 21;
passive_mode = true; // #######################################
main_sock = null;
main_ipEndPoint = null;
listening_sock = null;
data_sock = null;
data_ipEndPoint = null;
file = null;
bucket = "";
bytes_total = 0;
timeout = 10000; // 10 seconds
messages = "";
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="server">Server to connect to</param>
/// <param name="port">Port server is listening on</param>
/// <param name="user">Account to login as</param>
/// <param name="pass">Account password</param>
public FTP(string server, int port, string user, string pass)
{
this.server = server;
this.user = user;
this.pass = pass;
this.port = port;
passive_mode = true; // #######################################
main_sock = null;
main_ipEndPoint = null;
listening_sock = null;
data_sock = null;
data_ipEndPoint = null;
file = null;
bucket = "";
bytes_total = 0;
timeout = 10000; // 10 seconds
messages = "";
}
#endregion
/// <summary>
/// Connection status to the server
/// </summary>
public bool IsConnected
{
get
{
if (main_sock != null)
return main_sock.Connected;
return false;
}
}
/// <summary>
/// Returns true if the message buffer has data in it
/// </summary>
public bool MessagesAvailable
{
get
{
if(messages.Length > 0)
return true;
return false;
}
}
/// <summary>
/// Server messages if any, buffer is cleared after you access this property
/// </summary>
public string Messages
{
get
{
string tmp = messages;
messages = "";
return tmp;
}
}
/// <summary>
/// The response string from the last issued command
/// </summary>
public string ResponseString
{
get
{
return responseStr;
}
}
/// <summary>
/// The total number of bytes sent/recieved in a transfer
/// </summary>
public long BytesTotal // #######################################
{
get
{
return bytes_total;
}
}
/// <summary>
/// The size of the file being downloaded/uploaded (Can possibly be 0 if no size is available)
/// </summary>
public long FileSize // #######################################
{
get
{
return file_size;
}
}
/// <summary>
/// True: Passive mode [default]
/// False: Active Mode
/// </summary>
public bool PassiveMode // #######################################
{
get
{
return passive_mode;
}
set
{
passive_mode = value;
}
}
private void Fail()
{
Disconnect();
throw new Exception(responseStr);
}
private void SetBinaryMode(bool mode)
{
if (mode)
SendCommand("TYPE I");
else
SendCommand("TYPE A");
ReadResponse();
if (response != 200)
Fail();
}
private void SendCommand(string command)
{
Byte[] cmd = Encoding.ASCII.GetBytes((command + "\r\n").ToCharArray());
#if (FTP_DEBUG)
if (command.Length > 3 && command.Substring(0, 4) == "PASS")
Console.WriteLine("\rPASS xxx");
else
Console.WriteLine("\r" + command);
#endif
main_sock.Send(cmd, cmd.Length, 0);
}
private void FillBucket()
{
Byte[] bytes = new Byte[512];
long bytesgot;
int msecs_passed = 0; // #######################################
while(main_sock.Available < 1)
{
System.Threading.Thread.Sleep(50);
msecs_passed += 50;
// this code is just a fail safe option
// so the code doesn't hang if there is
// no data comming.
if (msecs_passed > timeout)
{
Disconnect();
throw new Exception("Timed out waiting on server to respond.");
}
}
while(main_sock.Available > 0)
{
bytesgot = main_sock.Receive(bytes, 512, 0);
bucket += Encoding.ASCII.GetString(bytes, 0, (int)bytesgot);
// this may not be needed, gives any more data that hasn't arrived
// just yet a small chance to get there.
System.Threading.Thread.Sleep(50);
}
}
private string GetLineFromBucket()
{
int i;
string buf = "";
if ((i = bucket.IndexOf('\n')) < 0)
{
while(i < 0)
{
FillBucket();
i = bucket.IndexOf('\n');
}
}
buf = bucket.Substring(0, i);
bucket = bucket.Substring(i + 1);
return buf;
}
// Any time a command is sent, use ReadResponse() to get the response
// from the server. The variable responseStr holds the entire string and
// the variable response holds the response number.
private void ReadResponse()
{
string buf;
messages = "";
while(true)
{
//buf = GetLineFromBucket();
buf = GetLineFromBucket();
#if (FTP_DEBUG)
Console.WriteLine(buf);
#endif
// the server will respond with "000-Foo bar" on multi line responses
// "000 Foo bar" would be the last line it sent for that response.
// Better example:
// "000-This is a multiline response"
// "000-Foo bar"
// "000 This is the end of the response"
if (Regex.Match(buf, "^[0-9]+ ").Success)
{
responseStr = buf;
response = int.Parse(buf.Substring(0, 3));
break;
}
else
messages += Regex.Replace(buf, "^[0-9]+-", "") + "\n";
}
}
// if you add code that needs a data socket, i.e. a PASV or PORT command required,
// call this function to do the dirty work. It sends the PASV or PORT command,
// parses out the port and ip info and opens the appropriate data socket
// for you. The socket variable is private Socket data_socket. Once you
// are done with it, be sure to call CloseDataSocket()
private void OpenDataSocket()
{
if (passive_mode) // #######################################
{
string[] pasv;
string server;
int port;
Connect();
SendCommand("PASV");
ReadResponse();
if (response != 227)
Fail();
try
{
int i1, i2;
i1 = responseStr.IndexOf('(') + 1;
i2 = responseStr.IndexOf(')') - i1;
pasv = responseStr.Substring(i1, i2).Split(',');
}
catch(Exception)
{
Disconnect();
throw new Exception("Malformed PASV response: " + responseStr);
}
if (pasv.Length < 6)
{
Disconnect();
throw new Exception("Malformed PASV response: " + responseStr);
}
server = String.Format("{0}.{1}.{2}.{3}", pasv[0], pasv[1], pasv[2], pasv[3]);
port = (int.Parse(pasv[4]) << 8) + int.Parse(pasv[5]);
try
{
#if (FTP_DEBUG)
Console.WriteLine("Data socket: {0}:{1}", server, port);
#endif
CloseDataSocket();
#if (FTP_DEBUG)
Console.WriteLine("Creating socket...");
#endif
data_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
#if (FTP_DEBUG)
Console.WriteLine("Resolving host");
#endif
data_ipEndPoint = new IPEndPoint(Dns.GetHostEntry(server).AddressList[0], port);
#if (FTP_DEBUG)
Console.WriteLine("Connecting..");
#endif
data_sock.Connect(data_ipEndPoint);
#if (FTP_DEBUG)
Console.WriteLine("Connected.");
#endif
}
catch(Exception ex)
{
throw new Exception("Failed to connect for data transfer: " + ex.Message);
}
}
else // #######################################
{
Connect();
try
{
#if (FTP_DEBUG)
Console.WriteLine("Data socket (active mode)");
#endif
CloseDataSocket();
#if (FTP_DEBUG)
Console.WriteLine("Creating listening socket...");
#endif
listening_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
#if (FTP_DEBUG)
Console.WriteLine("Binding it to local address/port");
#endif
// for the PORT command we need to send our IP address; let's extract it
// from the LocalEndPoint of the main socket, that's already connected
string sLocAddr = main_sock.LocalEndPoint.ToString();
int ix = sLocAddr.IndexOf(':');
if (ix < 0)
{
throw new Exception("Failed to parse the local address: " + sLocAddr);
}
string sIPAddr = sLocAddr.Substring(0, ix);
// let the system automatically assign a port number (setting port = 0)
System.Net.IPEndPoint localEP = new IPEndPoint(IPAddress.Parse(sIPAddr), 0);
listening_sock.Bind(localEP);
sLocAddr = listening_sock.LocalEndPoint.ToString();
ix = sLocAddr.IndexOf(':');
if (ix < 0)
{
throw new Exception("Failed to parse the local address: " + sLocAddr);
}
int nPort = int.Parse(sLocAddr.Substring(ix + 1));
#if (FTP_DEBUG)
Console.WriteLine("Listening on {0}:{1}", sIPAddr, nPort);
#endif
// start to listen for a connection request from the host (note that
// Listen is not blocking) and send the PORT command
listening_sock.Listen(1);
string sPortCmd = string.Format("PORT {0},{1},{2}",
sIPAddr.Replace('.', ','),
nPort / 256, nPort % 256);
SendCommand(sPortCmd);
ReadResponse();
if (response != 200)
Fail();
}
catch(Exception ex)
{
throw new Exception("Failed to connect for data transfer: " + ex.Message);
}
}
}
private void ConnectDataSocket() // #######################################
{
if (data_sock != null) // already connected (always so if passive mode)
return;
try
{
#if (FTP_DEBUG)
Console.WriteLine("Accepting the data connection.");
#endif
data_sock = listening_sock.Accept(); // Accept is blocking
listening_sock.Close();
listening_sock = null;
if (data_sock == null)
{
throw new Exception("Winsock error: " +
Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error()) );
}
#if (FTP_DEBUG)
Console.WriteLine("Connected.");
#endif
}
catch(Exception ex)
{
throw new Exception("Failed to connect for data transfer: " + ex.Message);
}
}
private void CloseDataSocket()
{
#if (FTP_DEBUG)
Console.WriteLine("Attempting to close data channel socket...");
#endif
if (data_sock != null)
{
if (data_sock.Connected)
{
#if (FTP_DEBUG)
Console.WriteLine("Closing data channel socket!");
#endif
data_sock.Close();
#if (FTP_DEBUG)
Console.WriteLine("Data channel socket closed!");
#endif
}
data_sock = null;
}
data_ipEndPoint = null;
}
/// <summary>
/// Closes all connections to the ftp server
/// </summary>
public void Disconnect()
{
CloseDataSocket();
if (main_sock != null)
{
if (main_sock.Connected)
{
SendCommand("QUIT");
main_sock.Close();
}
main_sock = null;
}
if (file != null)
file.Close();
main_ipEndPoint = null;
file = null;
}
/// <summary>
/// Connect to a ftp server
/// </summary>
/// <param name="server">IP or hostname of the server to connect to</param>
/// <param name="port">Port number the server is listening on</param>
/// <param name="user">Account name to login as</param>
/// <param name="pass">Password for the account specified</param>
public void Connect(string server, int port, string user, string pass)
{
this.server = server;
this.user = user;
this.pass = pass;
this.port = port;
Connect();
}
/// <summary>
/// Connect to a ftp server
/// </summary>
/// <param name="server">IP or hostname of the server to connect to</param>
/// <param name="user">Account name to login as</param>
/// <param name="pass">Password for the account specified</param>
public void Connect(string server, string user, string pass)
{
this.server = server;
this.user = user;
this.pass = pass;
Connect();
}
/// <summary>
/// Connect to an ftp server
/// </summary>
public void Connect()
{
if (server == null)
throw new Exception("No server has been set.");
if (user == null)
throw new Exception("No username has been set.");
if (main_sock != null)
if (main_sock.Connected)
return;
main_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
main_ipEndPoint = new IPEndPoint(Dns.GetHostEntry(server).AddressList[0], port);
try
{
main_sock.Connect(main_ipEndPoint);
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
ReadResponse();
if (response != 220)
Fail();
SendCommand("USER " + user);
ReadResponse();
switch(response)
{
case 331:
if (pass == null)
{
Disconnect();
throw new Exception("No password has been set.");
}
SendCommand("PASS " + pass);
ReadResponse();
if (response != 230)
Fail();
break;
case 230:
break;
}
return;
}
/// <summary>
/// Retrieves a list of files from the ftp server
/// </summary>
/// <returns>An ArrayList of files</returns>
public ArrayList List()
{
Byte[] bytes = new Byte[512];
string file_list = "";
long bytesgot = 0;
int msecs_passed = 0;
ArrayList list = new ArrayList();
Connect();
OpenDataSocket();
SendCommand("LIST");
ReadResponse();
//FILIPE MADUREIRA.
//Added response 125
switch(response)
{
case 125:
case 150:
break;
default:
CloseDataSocket();
throw new Exception(responseStr);
}
ConnectDataSocket(); // #######################################
while(data_sock.Available < 1)
{
System.Threading.Thread.Sleep(50);
msecs_passed += 50;
// this code is just a fail safe option
// so the code doesn't hang if there is
// no data comming.
if (msecs_passed > (timeout / 10))
{
//CloseDataSocket();
//throw new Exception("Timed out waiting on server to respond.");
//FILIPE MADUREIRA.
//If there are no files to list it gives timeout.
//So I wait less time and if no data is received, means that there are no files
break;//Maybe there are no files
}
}
while(data_sock.Available > 0)
{
bytesgot = data_sock.Receive(bytes, bytes.Length, 0);
file_list += Encoding.ASCII.GetString(bytes, 0, (int)bytesgot);
System.Threading.Thread.Sleep(50); // *shrug*, sometimes there is data comming but it isn't there yet.
}
CloseDataSocket();
ReadResponse();
if (response != 226)
throw new Exception(responseStr);
foreach(string f in file_list.Split('\n'))
{
if (f.Length > 0 && !Regex.Match(f, "^total").Success)
list.Add(f.Substring(0, f.Length - 1));
}
return list;
}
/// <summary>
/// Gets a file list only
/// </summary>
/// <returns>ArrayList of files only</returns>
public ArrayList ListFiles()
{
ArrayList list = new ArrayList();
foreach(string f in List())
{
//FILIPE MADUREIRA
//In Windows servers it is identified by <DIR>
if ((f.Length > 0))
{
if ((f[0] != 'd') && (f.ToUpper().IndexOf("<DIR>") < 0))
list.Add(f);
}
}
return list;
}
/// <summary>
/// Gets a directory list only
/// </summary>
/// <returns>ArrayList of directories only</returns>
public ArrayList ListDirectories()
{
ArrayList list = new ArrayList();
foreach(string f in List())
{
//FILIPE MADUREIRA
//In Windows servers it is identified by <DIR>
if (f.Length > 0)
{
if ((f[0] == 'd') || (f.ToUpper().IndexOf("<DIR>") >= 0))
list.Add(f);
}
}
return list;
}
/// <summary>
/// Returns the 'Raw' DateInformation in ftp format. (YYYYMMDDhhmmss). Use GetFileDate to return a DateTime object as a better option.
/// </summary>
/// <param name="fileName">Remote FileName to Query</param>
/// <returns>Returns the 'Raw' DateInformation in ftp format</returns>
public string GetFileDateRaw(string fileName)
{
Connect();
SendCommand("MDTM " + fileName);
ReadResponse();
if(response != 213)
{
#if (FTP_DEBUG)
Console.Write("\r" + responseStr);
#endif
throw new Exception(responseStr);
}
return (this.responseStr.Substring(4));
}
/// <summary>
/// GetFileDate will query the ftp server for the date of the remote file.
/// </summary>
/// <param name="fileName">Remote FileName to Query</param>
/// <returns>DateTime of the Input FileName</returns>
public DateTime GetFileDate(string fileName)
{
return ConvertFTPDateToDateTime(GetFileDateRaw(fileName));
}
private DateTime ConvertFTPDateToDateTime(string input)
{
if(input.Length < 14)
throw new ArgumentException("Input Value for ConvertFTPDateToDateTime method was too short.");
//YYYYMMDDhhmmss":
int year = Convert.ToInt16(input.Substring(0,4));
int month = Convert.ToInt16(input.Substring(4,2));
int day = Convert.ToInt16(input.Substring(6,2));
int hour = Convert.ToInt16(input.Substring(8,2));
int min = Convert.ToInt16(input.Substring(10,2));
int sec = Convert.ToInt16(input.Substring(12,2));
return new DateTime(year, month, day, hour, min, sec);
}
/// <summary>
/// Get the working directory on the ftp server
/// </summary>
/// <returns>The working directory</returns>
public string GetWorkingDirectory()
{
//PWD - print working directory
Connect();
SendCommand("PWD");
ReadResponse();
if(response != 257)
throw new Exception(responseStr);
string pwd;
try
{
pwd = responseStr.Substring(responseStr.IndexOf("\"", 0) + 1);//5);
pwd = pwd.Substring(0, pwd.LastIndexOf("\""));
pwd = pwd.Replace("\"\"", "\""); // directories with quotes in the name come out as "" from the server
}
catch(Exception ex)
{
throw new Exception("Uhandled PWD response: " + ex.Message);
}
return pwd;
}
/// <summary>
/// Change to another directory on the ftp server
/// </summary>
/// <param name="path">Directory to change to</param>
public void ChangeDir(string path)
{
Connect();
SendCommand("CWD " + path);
ReadResponse();
if (response != 250)
{
#if (FTP_DEBUG)
Console.Write("\r" + responseStr);
#endif
throw new Exception(responseStr);
}
}
/// <summary>
/// Create a directory on the ftp server
/// </summary>
/// <param name="dir">Directory to create</param>
public void MakeDir(string dir)
{
Connect();
SendCommand("MKD " + dir);
ReadResponse();
switch(response)
{
case 257:
case 250:
break;
default:
#if (FTP_DEBUG)
Console.Write("\r" + responseStr);
#endif
throw new Exception(responseStr);
}
}
/// <summary>
/// Remove a directory from the ftp server
/// </summary>
/// <param name="dir">Name of directory to remove</param>
public void RemoveDir(string dir)
{
Connect();
SendCommand("RMD " + dir);
ReadResponse();
if (response != 250)
{
#if (FTP_DEBUG)
Console.Write("\r" + responseStr);
#endif
throw new Exception(responseStr);
}
}
/// <summary>
/// Remove a file from the ftp server
/// </summary>
/// <param name="filename">Name of the file to delete</param>
public void RemoveFile(string filename)
{
Connect();
SendCommand("DELE " + filename);
ReadResponse();
if (response != 250)
{
#if (FTP_DEBUG)
Console.Write("\r" + responseStr);
#endif
throw new Exception(responseStr);
}
}
/// <summary>
/// Rename a file on the ftp server
/// </summary>
/// <param name="oldfilename">Old file name</param>
/// <param name="newfilename">New file name</param>
public void RenameFile(string oldfilename, string newfilename) // #######################################
{
Connect();
SendCommand("RNFR " + oldfilename);
ReadResponse();
if (response != 350)
{
#if (FTP_DEBUG)
Console.Write("\r" + responseStr);
#endif
throw new Exception(responseStr);
}
else
{
SendCommand("RNTO " + newfilename);
ReadResponse();
if (response != 250)
{
#if (FTP_DEBUG)
Console.Write("\r" + responseStr);
#endif
throw new Exception(responseStr);
}
}
}
/// <summary>
/// Get the size of a file (Provided the ftp server supports it)
/// </summary>
/// <param name="filename">Name of file</param>
/// <returns>The size of the file specified by filename</returns>
public long GetFileSize(string filename)
{
Connect();
SendCommand("TYPE I");
ReadResponse();
SendCommand("SIZE " + filename);
ReadResponse();
if (response != 213)
{
#if (FTP_DEBUG)