FTP operation class

xiaoxiao2021-04-05  257

Using system; using system.text; using system.net.sockets;

Namespace ListSynch {///

/// ftp client /// /// Default constructor /// public FTPClient () {strremoteHost = ""; strremoteuser = "; strremotePass ="; strremoteport = 21; bconnected = false;}

///

/// Constructor /// /// /// // / /// /// 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 /// private string strremotehost; public string remotehost {get {return strremotehost;} set {strremotehost = value;}} /// /// FTP server port /// Private Int strreMoteport; public int recordport {get {return strremoteport;} set {strremoteport = value;}} /// /// Current server directory /// / private string strRemotePath; public string RemotePath {get {return strRemotePath;} set {strRemotePath = value;}} /// /// login user account /// 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 /// private boolean bconnected; public bool connection {get {return bconnected;}} #ENDREG Ion

#region link ///

/// establish connection /// 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 /// public void disconnect () {if (SocketControl! = null) {sendcommand ("quit");} closesocketconnect ();}

#ndregion

#REGION transmission mode

///

/// Transfer mode: binary type, ASCII type /// public enum transfertype {binary, ASCII};

///

/// Setting transfer mode /// Transfer mode 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 /// /// Transfer mode public transfertype gettransfertype () {return trType;} #ENDREGION

#Region file operation ///

/// get a file list /// ///

// 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 /// /// file name /// file size 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 /// /// To delete the file name 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) /// /// Old file name /// New file name 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 /// /// File name Matching string /// local directory (not / end) 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 /// /// File name to download /// Local directory (not / end) /// Save file name 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 /// /// local directory (not / end) /// filename matching characters (can contain * and?) 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 /// /// Local file name 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 /// /// directory name public void mkdir (String strDirName) {if (! Bconnected) {connection ("" MKD " strDirName; if (IrePlyCode! = 257) {throw new oException (4));}} /// /// Delete Directory /// /// directory name public void rmdir (string strdirname) {if (! bconnected) {connection ();} sendcommand ("RMD" strDirname ); If (IrePlyCode! = 250) {throw new oException (Strreply.Substring (4));}} /// /// change directory /// /// New work directory Name 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) /// private string strreply; /// /// server returns the response code /// private int inmarycode; /// /// Connected socket /// /// Transfer mode /// private transfertype Trtype; /// // // receive and send data Buffer /// private static int block_size = 512; byte [] buffer = new byte [block_size]; /// /// encoding method /// Encoding ASCII = Encoding. ASCII; # endregion # Region internal function /// /// Record a line response string in strreply and strmsg /// 应 应 lCode /// private void readreply () {strmsg = ""; Strreply = readline (); Ireplycode = int32.parse (Strreply.Substring (0, 3));

///

/// Establisted Socket /// /// data connection socket 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) /// private void clossoSocketConnect () {if (socketcontrol! = null) {socketcontrol.close (); socketcontrol = null;} BConnected = false;} /// /// Read all strings returned by Socket /// /// Character Serial String Readline, which contains the reply code 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 /// /// Command private void send skill (string strands) {byte [] cmdbytes = encoding.ascii.getbytes ((strcommand "/ r / n" ) .Tochararray ()); socketcontrol.send (cmdbytes, cmdbytes.length, 0); readReply ();}

#ndregion}}}

转载请注明原文地址:https://www.9cbs.com/read-131992.html

New Post(0)