Using system; using system.text; using system.net.sockets;
Namespace ListSynch {/// /// ftp client /// ////////// /// Default constructor /// summary> public FTPClient () {strremoteHost = ""; strremoteuser = "; strremotePass ="; strremoteport = 21; bconnected = false;}
/// /// Constructor /// summary> /// param> /// param> // / param> /// param> /// param> public ftpclient (String Remotehost, String remotePath, string remoteUser, string remotePass, int remotePort) {strRemoteHost = remoteHost; strRemotePath = remotePath; strRemoteUser = remoteUser; strRemotePass = remotePass; strRemotePort = remotePort; Connect ();} #endregion
#Region Login /// /// FTP server IP address /// summary> private string strremotehost; public string remotehost {get {return strremotehost;} set {strremotehost = value;}} /// /// FTP server port /// summary> Private Int strreMoteport; public int recordport {get {return strremoteport;} set {strremoteport = value;}} /// /// Current server directory /// / summary> private string strRemotePath; public string RemotePath {get {return strRemotePath;} set {strRemotePath = value;}} /// /// login user account /// summary> private string strRemoteUser; Public String Remoteuser {set {strremoteuser = value;}} /// /// User login password /////mary> private string strreMotepass; public string remotepass {set {strreMotepass = value;}} /// / / / Whether to log in /// summary> private boolean bconnected; public bool connection {get {return bconnected;}} #ENDREG Ion
#region link /// /// establish connection /// summary> public void Connect () {socketControl = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ep = new IPEndPoint (DNS.Resolve (strreMotehost) .addresslist [0], strreMoteport); // link try {socketcontrol.connect (EP)} ("COULDN't Connect To Remote Server);}
// Get the response code readReply (); if (IreplyCode! = 220) {disconnect (); throw new oException (4));}
// Log in to SendCommand ("User" Stremoteuser; if (! (Remecode == 331 || IreplyCode == 230)) {CloseSocketConnect (); // Close connection throw new oException (Strreply.Substring (4));} if (iReplyCode = 230!) {SendCommand ( "PASS" strRemotePass); if ((iReplyCode == 230 || iReplyCode == 202)!) {CloseSocketConnect (); // close the connection throw new IOException (strReply.Substring ( 4));}} bconnected = true; // Switch to the directory chDIR (StrremotePath);}
/// /// Close connection /// summary> public void disconnect () {if (SocketControl! = null) {sendcommand ("quit");} closesocketconnect ();}
#ndregion
#REGION transmission mode
/// /// Transfer mode: binary type, ASCII type /// summary> public enum transfertype {binary, ASCII};
/// /// Setting transfer mode /// //// Transfer mode param> public void settransfertype (TTTYPE TTTTYPE) {ix (tttype == Transfertype .Bery) {sendcommand ("Type I"); // binary type transfer} else {sendcommand ("Type A"); // ASCII type transfer} if (IrePlyCode! = 200) {throw new ioException (strreply.substring 4));} else {TRTYPE = TTTTYPE;}}
/// /// Get transmission mode /// summary> /// Transfer mode returns> public transfertype gettransfertype () {return trType;} #ENDREGION
#Region file operation /// /// get a file list /// summary> ///
// Get the result strmsg = ""; while (true) {int bytes = socketdata.receive (buffer, buffer.length, 0); strmsg = ascii.getstring (buffer, 0, ibytes); if (Ibytes
/// /// Get file size /// summary> /// file name param> /// file size returns> private long GetFileSize (string strFileName) {if (bConnected!) {Connect ();} SendCommand ( "SIZE" Path.GetFileName (strFileName)); long lSize = 0; if (iReplyCode == 213) {lSize = Int64.Parse ( Strreply.substring (4));} else {throw new oException (Strreply.Substring (4));} return lsize;}
/// /// Delete /// summary> /// To delete the file name param> public void delete (string strfilename) {if (! bconnected) { Connect (); "dele" strfilename; if (Ireplycode! = 250) {throw new oException (Strreply.Substring (4));}}
/// /// Rename (if the new file name is reintegrated with the file, will overwrite the existing file) /// summary> /// Old file name parame> /// New file name param> public void rename (string stroldfilename) {if (! bconnected) {connect ();} sendcommand ("RNFR" StroldFileName); if (IrePlyCode! = 350) {throw new oException (Strreply.Substring (4));} // If the new file name is retrunly named, the original file SendCommand ("RNTO" StrneWFileName) ; If (IreplyCode! = 250) {throw new oException (4));}} # endregion # region upload and download /// /// download a batch of files /// summary> /// File name Matching string param> /// local directory (not / end) param> public void get (String StrfileNamemask String strfolder) {if (! bconnected) {connection ();} string [] strfiles = dir (strfilenamemask; foreach (string strfile in strfiles) {if (! strfile.equals (")) // General The last element of Strfiles may be empty string {GET (Strfile, strfolder, strfile);}}}
/// /// Download a file /// summary> /// File name to download param> /// Local directory (not / end) param> /// Save file name param> public void get (string strremotefilename, string strover, string string string string string string string string "{ix ! bConnected) {Connect ();} SetTransferType (TransferType.Binary); if (strLocalFileName.Equals ( "")) {strLocalFileName = strRemoteFileName;} if (! File.Exists (strLocalFileName)) {Stream st = File.Create ( strLocalFileName); st.Close ();} FileStream output = new FileStream (strFolder "//" strLocalFileName, FileMode.Create); Socket socketData = CreateDataSocket (); SendCommand ( "RETR" strRemoteFileName); if ((! iReplyCode == 150 || iReplyCode == 125 || iReplyCode == 226 || iReplyCode == 250)) {throw new IOException (strReply.Substring (4));} while (true) {int iBytes = socketData.Receive ( Buffer, buffer.length, 0); Output.write (buffer, 0, ibytes) ; Ibytes <= 0) {Break;}} Output.close (); if (socketData.Connected) {socketData.close ();} if (! (IReplyCode == 250) { ReadReply (); if (! (Remecode == 226 || iReplyCode == 250)) {throw new oException (Strreply.Substring (4));}}}
/// /// upload a batch of files /// summary> /// local directory (not / end) param> /// filename matching characters (can contain * and?) param> public void Put (string strFolder, string strFileNameMask) {string [] strFiles = Directory.GetFiles (strFolder, strFileNameMask); foreach (string strFile in strFiles ) {// Strfile is a complete file name (including path) PUT (Strfile);}} /// /// upload a file /// summary> /// Local file name param> public void put (string strfilename) {if (! Bconnected) {connection ();} Socket SocketData = createDataSocket (); sendcommand ("stor" path.getFileName (StrfileName); if ( ! (iReplyCode == 125 || iReplyCode == 150)) {throw new IOException (strReply.Substring (4));} FileStream input = new FileStream (strFileName, FileMode.Open); int iBytes = 0; while ((iBytes = INPUT.READ (Buffer, 0, Buffer.length)> 0) {socketData.send (buffer, ibytes, 0);} infut.close (); if (socketData.connected) {socketData.c Lose ();} if (! (ireplycode == 226 || Ireplycode == 250)) {readReply (); if (! (remecode == 226 || iReplyCode == 250)) {throw new oException (strreply.substring (4));}}} #ENDREGION
#REGON directory operation /// /// creation directory /// summary> /// directory name param> public void mkdir (String strDirName) {if (! Bconnected) {connection ("" MKD " strDirName; if (IrePlyCode! = 257) {throw new oException (4));}} /// /// Delete Directory /// summary> /// directory name param> public void rmdir (string strdirname) {if (! bconnected) {connection ();} sendcommand ("RMD" strDirname ); If (IrePlyCode! = 250) {throw new oException (Strreply.Substring (4));}} /// /// change directory /// summary> /// New work directory Name param> public void chdir (strDirname.equals (". ") || strDirname.equals (")) {return;} f (! bconnected) { Connect (); "CWD" strDirName; if (IreplyCode! = 250) {throw new oException (4));} this.strremotePath = strDirciRName;} #ENDREGION
#REGION internal variable /// /// server returns message (including response code) /// ///////////// /// server returns a response information (included Answers) /// summary> private string strreply; /// /// server returns the response code /// summary> private int inmarycode; /// /// Connected socket /// /////// /// Transfer mode /// summary> private transfertype Trtype; /// // // receive and send data Buffer /// summary> private static int block_size = 512; byte [] buffer = new byte [block_size]; /// /// encoding method /// summary> Encoding ASCII = Encoding. ASCII; # endregion # Region internal function /// /// Record a line response string in strreply and strmsg /// 应 应 lCode /// summary> private void readreply () {strmsg = ""; Strreply = readline (); Ireplycode = int32.parse (Strreply.Substring (0, 3));
/// /// Establisted Socket /// summary> /// data connection socket returns> private socket createdataocket () {sendcommand ("PASV"); if ("PASV"); ! iReplyCode = 227) {throw new IOException (strReply.Substring (4));} int index1 = strReply.IndexOf ( '('); int index2 = strReply.IndexOf ( ')'); string ipData = strReply.Substring ( Index1 1, Index2-index1-1); int [] parts = new int [6]; int LEN = ipdata.length; int linecount = 0; string buf = ""; for (int i = 0; i
/// /// Close the Socket connection (for logging in previous) /// summary> private void clossoSocketConnect () {if (socketcontrol! = null) {socketcontrol.close (); socketcontrol = null;} BConnected = false;} /// /// Read all strings returned by Socket /// summary> /// Character Serial String Readline, which contains the reply code returns> Private String Readline ) {While {INT IBYTES = SocketControl.Receive (Buffer, Buffer.Length, 0); strmsg = ascii.getstring (buffer, 0, ibytes); if (ibytes 2) {strmsg = mess [mess.length-2]; // seperator [0] 10. The newline character is made up of 13 and 0, although there is no string after separation, //, but also assigns an empty string to the back (and the last one) string array, // So the last Mess is Useless empty string / / but why not directly take Mess [0], because only the last line of character string response code and information have space} else {strmsg = Mess [0];} if (!! Strmsg.substring) 3, 1) .Equals (")) // Returns the string is correct to answer the answer (such as 220 start, after connecting a space, then the greeting string) {Return Readline ();} return strmsg;} / // /// Send commands and get answers and last line of response strings /// summary> /// Command param> private void send skill (string strands) {byte [] cmdbytes = encoding.ascii.getbytes ((strcommand "/ r / n" ) .Tochararray ()); socketcontrol.send (cmdbytes, cmdbytes.length, 0); readReply ();}
#ndregion}}}