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
| using System;
using System.Net;
using System.IO;
using System.Text;
using System.Net.Sockets;
using System.Diagnostics;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
/*
* FTP Client library in C#
* Author: Jaimon Mathew
* mailto:jaimonmathew@rediffmail.com
* http://www.csharphelp.com/archives/archive9.html
*
* Addapted for use by Dan Glass 07/03/03
*/
namespace Project
{
public class FtpClient
{
public class FtpException : Exception
{
public FtpException(string message) : base(message) { }
public FtpException(string message, Exception innerException) : base(message, innerException) { }
}
private static int BUFFER_SIZE = 512;
private static Encoding ASCII = Encoding.ASCII;
private bool verboseDebugging = false;
// defaults
private string server = "localhost";
private string remotePath = ".";
private string username = "anonymous";
private string password = "anonymous@anonymous.net";
private string message = null;
private string result = null;
private int port = 21;
private int bytes = 0;
private int resultCode = 0;
private bool loggedin = false;
private bool binMode = false;
private Byte[] buffer = new Byte[BUFFER_SIZE];
private Socket clientSocket = null;
private int timeoutSeconds = 10;
/// <summary>
/// Default contructor
/// </summary>
public FtpClient()
{
}
/// <summary>
///
/// </summary>
/// <param name="server"></param>
/// <param name="username"></param>
/// <param name="password"></param>
public FtpClient(string server, string username, string password)
{
this.server = server;
this.username = username;
this.password = password;
}
/// <summary>
///
/// </summary>
/// <param name="server"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="timeoutSeconds"></param>
/// <param name="port"></param>
public FtpClient(string server, string username, string password, int timeoutSeconds, int port)
{
this.server = server;
this.username = username;
this.password = password;
this.timeoutSeconds = timeoutSeconds;
this.port = port;
}
/// <summary>
/// Display all communications to the debug log
/// </summary>
public bool VerboseDebugging
{
get
{
return this.verboseDebugging;
}
set
{
this.verboseDebugging = value;
}
}
/// <summary>
/// Remote server port. Typically TCP 21
/// </summary>
public int Port
{
get
{
return this.port;
}
set
{
this.port = value;
}
}
/// <summary>
/// Timeout waiting for a response from server, in seconds.
/// </summary>
public int Timeout
{
get
{
return this.timeoutSeconds;
}
set
{
this.timeoutSeconds = value;
}
}
/// <summary>
/// Gets and Sets the name of the FTP server.
/// </summary>
/// <returns></returns>
public string Server
{
get
{
return this.server;
}
set
{
this.server = value;
}
}
/// <summary>
/// Gets and Sets the port number.
/// </summary>
/// <returns></returns>
public int RemotePort
{
get
{
return this.port;
}
set
{
this.port = value;
}
}
/// <summary>
/// GetS and Sets the remote directory.
/// </summary>
public string RemotePath
{
get
{
return this.remotePath;
}
set
{
this.remotePath = value;
}
}
/// <summary>
/// Gets and Sets the username.
/// </summary>
public string Username
{
get
{
return this.username;
}
set
{
this.username = value;
}
}
/// <summary>
/// Gets and Set the password.
/// </summary>
public string Password
{
get
{
return this.password;
}
set
{
this.password = value;
}
}
/// <summary>
/// If the value of mode is true, set binary mode for downloads, else, Ascii mode.
/// </summary>
public bool BinaryMode
{
get
{
return this.binMode;
}
set
{
if (this.binMode == value) return;
if (value)
sendCommand("TYPE I");
else
sendCommand("TYPE A");
if (this.resultCode != 200) throw new FtpException(result.Substring(4));
}
}
/// <summary>
/// Login to the remote server.
/// </summary>
public void Login()
{
if (this.loggedin) this.Close();
Debug.WriteLine("Opening connection to " + this.server, "FtpClient");
IPAddress addr = null;
IPEndPoint ep = null;
try
{
this.clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
addr = Dns.Resolve(this.server).AddressList[0];
ep = new IPEndPoint(addr, this.port);
this.clientSocket.Connect(ep);
}
catch (Exception ex)
{
// doubtfull
if (this.clientSocket != null && this.clientSocket.Connected) this.clientSocket.Close();
throw new FtpException("Couldn't connect to remote server", ex);
}
this.readResponse();
if (this.resultCode != 220)
{
this.Close();
throw new FtpException(this.result.Substring(4));
}
this.sendCommand("USER " + username);
if (!(this.resultCode == 331 || this.resultCode == 230))
{
this.cleanup();
throw new FtpException(this.result.Substring(4));
}
if (this.resultCode != 230)
{
this.sendCommand("PASS " + password);
if (!(this.resultCode == 230 || this.resultCode == 202))
{
this.cleanup();
throw new FtpException(this.result.Substring(4));
}
}
this.loggedin = true;
Debug.WriteLine("Connected to " + this.server, "FtpClient");
this.ChangeDir(this.remotePath);
}
/// <summary>
/// Close the FTP connection.
/// </summary>
public void Close()
{
Debug.WriteLine("Closing connection to " + this.server, "FtpClient");
if (this.clientSocket != null)
{
this.sendCommand("QUIT");
}
this.cleanup();
}
/// <summary>
/// Return a string array containing the remote directory's file list.
/// </summary>
/// <returns></returns>
public string[] GetFileList()
{
return this.GetFileList("*.*");
}
/// <summary>
/// Return a string array containing the remote directory's file list.
/// </summary>
/// <param name="mask"></param>
/// <returns></returns>
public string[] GetFileList(string mask)
{
if (!this.loggedin) this.Login();
Socket cSocket = createDataSocket();
this.sendCommand("NLST " + mask);
if (!(this.resultCode == 150 || this.resultCode == 125)) throw new FtpException(this.result.Substring(4));
this.message = "";
DateTime timeout = DateTime.Now.AddSeconds(this.timeoutSeconds);
while (timeout > DateTime.Now)
{
int bytes = cSocket.Receive(buffer, buffer.Length, 0);
this.message += ASCII.GetString(buffer, 0, bytes);
if (bytes < this.buffer.Length) break;
}
string[] msg = this.message.Replace("\r", "").Split('\n');
cSocket.Close();
if (this.message.IndexOf("No such file or directory") != -1)
msg = new string[] { };
this.readResponse();
if (this.resultCode != 226)
msg = new string[] { };
// throw new FtpException(result.Substring(4));
return msg;
}
/// <summary>
/// Return the size of a file.
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public long GetFileSize(string fileName)
{
if (!this.loggedin) this.Login();
this.sendCommand("SIZE " + fileName);
long size = 0;
if (this.resultCode == 213)
size = long.Parse(this.result.Substring(4));
else
throw new FtpException(this.result.Substring(4));
return size;
}
/// <summary>
/// Download a file to the Assembly's local directory,
/// keeping the same file name.
/// </summary>
/// <param name="remFileName"></param>
public void Download(string remFileName)
{
this.Download(remFileName, "", false);
}
/// <summary>
/// Download a remote file to the Assembly's local directory,
/// keeping the same file name, and set the resume flag.
/// </summary>
/// <param name="remFileName"></param>
/// <param name="resume"></param>
public void Download(string remFileName, Boolean resume)
{
this.Download(remFileName, "", resume);
}
/// <summary>
/// Download a remote file to a local file name which can include
/// a path. The local file name will be created or overwritten,
/// but the path must exist.
/// </summary>
/// <param name="remFileName"></param>
/// <param name="locFileName"></param>
public void Download(string remFileName, string locFileName)
{
this.Download(remFileName, locFileName, false);
}
/// <summary>
/// Download a remote file to a local file name which can include
/// a path, and set the resume flag. The local file name will be
/// created or overwritten, but the path must exist.
/// </summary>
/// <param name="remFileName"></param>
/// <param name="locFileName"></param>
/// <param name="resume"></param>
public void Download(string remFileName, string locFileName, Boolean resume)
{
if (!this.loggedin) this.Login();
this.BinaryMode = true;
Debug.WriteLine("Downloading file " + remFileName + " from " + server + "/" + remotePath, "FtpClient");
if (locFileName.Equals(""))
{
locFileName = remFileName;
}
FileStream output = null;
if (!File.Exists(locFileName))
output = File.Create(locFileName);
else
output = new FileStream(locFileName, FileMode.Open);
Socket cSocket = createDataSocket();
long offset = 0;
if (resume)
{
offset = output.Length;
if (offset > 0)
{
this.sendCommand("REST " + offset);
if (this.resultCode != 350)
{
//Server dosnt support resuming
offset = 0;
Debug.WriteLine("Resuming not supported:" + result.Substring(4), "FtpClient");
}
else
{
Debug.WriteLine("Resuming at offset " + offset, "FtpClient");
output.Seek(offset, SeekOrigin.Begin);
}
}
}
this.sendCommand("RETR " + remFileName);
if (this.resultCode != 150 && this.resultCode != 125)
{
throw new FtpException(this.result.Substring(4));
}
DateTime timeout = DateTime.Now.AddSeconds(this.timeoutSeconds);
while (timeout > DateTime.Now)
{
this.bytes = cSocket.Receive(buffer, buffer.Length, 0);
output.Write(this.buffer, 0, this.bytes);
if (this.bytes <= 0)
{
break;
}
}
output.Close();
if (cSocket.Connected) cSocket.Close();
this.readResponse();
if (this.resultCode != 226 && this.resultCode != 250)
throw new FtpException(this.result.Substring(4));
}
/// <summary>
/// Upload a file.
/// </summary>
/// <param name="fileName"></param>
public void Upload(string fileName)
{
this.Upload(fileName, false);
}
/// <summary>
/// Upload a file and set the resume flag.
/// </summary>
/// <param name="fileName"></param>
/// <param name="resume"></param>
public void Upload(string fileName, bool resume)
{
if (!this.loggedin) this.Login();
Socket cSocket = null;
long offset = 0;
if (resume)
{
try
{
this.BinaryMode = true;
offset = GetFileSize(Path.GetFileName(fileName));
}
catch (Exception)
{
// file not exist
offset = 0;
}
}
// open stream to read file
FileStream input = new FileStream(fileName, FileMode.Open);
if (resume && input.Length < offset)
{
// different file size
Debug.WriteLine("Overwriting " + fileName, "FtpClient");
offset = 0;
}
else if (resume && input.Length == offset)
{
// file done
input.Close();
Debug.WriteLine("Skipping completed " + fileName + " - turn resume off to not detect.", "FtpClient");
return;
}
// dont create untill we know that we need it
cSocket = this.createDataSocket();
if (offset > 0)
{
this.sendCommand("REST " + offset);
if (this.resultCode != 350)
{
Debug.WriteLine("Resuming not supported", "FtpClient");
offset = 0;
}
}
this.sendCommand("STOR " + Path.GetFileName(fileName));
if (this.resultCode != 125 && this.resultCode != 150) throw new FtpException(result.Substring(4));
if (offset != 0)
{
Debug.WriteLine("Resuming at offset " + offset, "FtpClient");
input.Seek(offset, SeekOrigin.Begin);
}
Debug.WriteLine("Uploading file " + fileName + " to " + remotePath, "FtpClient");
while ((bytes = input.Read(buffer, 0, buffer.Length)) > 0)
{
cSocket.Send(buffer, bytes, 0);
}
input.Close();
if (cSocket.Connected)
{
cSocket.Close();
}
this.readResponse();
if (this.resultCode != 226 && this.resultCode != 250) throw new FtpException(this.result.Substring(4));
}
/// <summary>
/// Upload a directory and its file contents
/// </summary>
/// <param name="path"></param>
/// <param name="recurse">Whether to recurse sub directories</param>
public void UploadDirectory(string path, bool recurse)
{
this.UploadDirectory(path, recurse, "*.*");
}
/// <summary>
/// Upload a directory and its file contents
/// </summary>
/// <param name="path"></param>
/// <param name="recurse">Whether to recurse sub directories</param>
/// <param name="mask">Only upload files of the given mask - everything is '*.*'</param>
public void UploadDirectory(string path, bool recurse, string mask)
{
string[] dirs = path.Replace("/", @"\").Split('\\');
string rootDir = dirs[dirs.Length - 1];
// make the root dir if it doed not exist
if (this.GetFileList(rootDir).Length < 1) this.MakeDir(rootDir);
this.ChangeDir(rootDir);
foreach (string file in Directory.GetFiles(path, mask))
{
this.Upload(file, true);
}
if (recurse)
{
foreach (string directory in Directory.GetDirectories(path))
{
this.UploadDirectory(directory, recurse, mask);
}
}
this.ChangeDir("..");
}
/// <summary>
/// Delete a file from the remote FTP server.
/// </summary>
/// <param name="fileName"></param>
public void DeleteFile(string fileName)
{
if (!this.loggedin) this.Login();
this.sendCommand("DELE " + fileName);
if (this.resultCode != 250) throw new FtpException(this.result.Substring(4));
Debug.WriteLine("Deleted file " + fileName, "FtpClient");
}
/// <summary>
/// Rename a file on the remote FTP server.
/// </summary>
/// <param name="oldFileName"></param>
/// <param name="newFileName"></param>
/// <param name="overwrite">setting to false will throw exception if it exists</param>
public void RenameFile(string oldFileName, string newFileName, bool overwrite)
{
if (!this.loggedin) this.Login();
this.sendCommand("RNFR " + oldFileName);
if (this.resultCode != 350) throw new FtpException(this.result.Substring(4));
if (!overwrite && this.GetFileList(newFileName).Length > 0) throw new FtpException("File already exists");
this.sendCommand("RNTO " + newFileName);
if (this.resultCode != 250) throw new FtpException(this.result.Substring(4));
Debug.WriteLine("Renamed file " + oldFileName + " to " + newFileName, "FtpClient");
}
/// <summary>
/// Create a directory on the remote FTP server.
/// </summary>
/// <param name="dirName"></param>
public void MakeDir(string dirName)
{
if (!this.loggedin) this.Login();
this.sendCommand("MKD " + dirName);
if (this.resultCode != 250 && this.resultCode != 257) throw new FtpException(this.result.Substring(4));
Debug.WriteLine("Created directory " + dirName, "FtpClient");
}
/// <summary>
/// Delete a directory on the remote FTP server.
/// </summary>
/// <param name="dirName"></param>
public void RemoveDir(string dirName)
{
if (!this.loggedin) this.Login();
this.sendCommand("RMD " + dirName);
if (this.resultCode != 250) throw new FtpException(this.result.Substring(4));
Debug.WriteLine("Removed directory " + dirName, "FtpClient");
}
/// <summary>
/// Change the current working directory on the remote FTP server.
/// </summary>
/// <param name="dirName"></param>
public void ChangeDir(string dirName)
{
if (dirName == null || dirName.Equals(".") || dirName.Length == 0)
{
return;
}
if (!this.loggedin) this.Login();
this.sendCommand("CWD " + dirName);
if (this.resultCode != 250) throw new FtpException(result.Substring(4));
this.sendCommand("PWD");
if (this.resultCode != 257) throw new FtpException(result.Substring(4));
// gonna have to do better than this....
this.remotePath = this.message.Split('"')[1];
Debug.WriteLine("Current directory is " + this.remotePath, "FtpClient");
}
/// <summary>
///
/// </summary>
private void readResponse()
{
this.message = "";
this.result = this.readLine();
if (this.result.Length > 3)
this.resultCode = int.Parse(this.result.Substring(0, 3));
else
this.result = null;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private string readLine()
{
while (true)
{
this.bytes = clientSocket.Receive(this.buffer, this.buffer.Length, 0);
this.message += ASCII.GetString(this.buffer, 0, this.bytes);
if (this.bytes < this.buffer.Length)
{
break;
}
}
string[] msg = this.message.Split('\n');
if (this.message.Length > 2)
this.message = msg[msg.Length - 2];
else
this.message = msg[0];
if (this.message.Length > 4 && !this.message.Substring(3, 1).Equals(" ")) return this.readLine();
if (this.verboseDebugging)
{
for (int i = 0; i < msg.Length - 1; i++)
{
Debug.Write(msg[i], "FtpClient");
}
}
return message;
}
/// <summary>
///
/// </summary>
/// <param name="command"></param>
private void sendCommand(String command)
{
if (this.verboseDebugging) Debug.WriteLine(command, "FtpClient");
Byte[] cmdBytes = Encoding.ASCII.GetBytes((command + "\r\n").ToCharArray());
clientSocket.Send(cmdBytes, cmdBytes.Length, 0);
this.readResponse();
}
/// <summary>
/// when doing data transfers, we need to open another socket for it.
/// </summary>
/// <returns>Connected socket</returns>
private Socket createDataSocket()
{
this.sendCommand("PASV");
if (this.resultCode != 227) throw new FtpException(this.result.Substring(4));
int index1 = this.result.IndexOf('(');
int index2 = this.result.IndexOf(')');
string ipData = this.result.Substring(index1 + 1, index2 - index1 - 1);
int[] parts = new int[6];
int len = ipData.Length;
int partCount = 0;
string buf = "";
for (int i = 0; i < len && partCount <= 6; i++)
{
char ch = char.Parse(ipData.Substring(i, 1));
if (char.IsDigit(ch))
buf += ch;
else if (ch != ',')
throw new FtpException("Malformed PASV result: " + result);
if (ch == ',' || i + 1 == len)
{
try
{
parts[partCount++] = int.Parse(buf);
buf = "";
}
catch (Exception ex)
{
throw new FtpException("Malformed PASV result (not supported?): " + this.result, ex);
}
}
}
string ipAddress = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3];
int port = (parts[4] << 8) + parts[5];
Socket socket = null;
IPEndPoint ep = null;
try
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ep = new IPEndPoint(Dns.Resolve(ipAddress).AddressList[0], port);
socket.Connect(ep);
}
catch (Exception ex)
{
// doubtfull....
if (socket != null && socket.Connected) socket.Close();
throw new FtpException("Can't connect to remote server", ex);
}
return socket;
}
/// <summary>
/// Always release those sockets.
/// </summary>
private void cleanup()
{
if (this.clientSocket != null)
{
this.clientSocket.Close();
this.clientSocket = null;
}
this.loggedin = false;
}
....
} |
Partager