FTP upload function in C #

xiaoxiao2021-03-06  178

/ *Ftpfactory.csbetter View with Tab Space = 4

Written by Jaimon Mathew (jaimonmathew@rediffmail.com) Rolander, Dan (Dan.Rolander@marriott.com) has modified the downloadmethod to cope with file name with path information. He also providedthe XML comments so that the library provides Intellisense descriptions.

Use the folcom: library /out:ftplib.dll /r:system.dll ftpFactory.cs * /

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

Namespace fTPLIB {

Public class ftpFactory {

Private String Remotehost, RemotePath, Remoteuser, RemotePass, Mes; Private Int RemotEport, Bytes; Private Socket ClientSocket

Private int RetValue; private boolean debug; private bolean logined;

Private static int block_size = 512;

Byte [] buffer = new byte [block_size]; Encoding ascii = encoding.ascii;

Public ftpFactory () {

Remotehost = "localhost"; remotepath = "; remoteuser =" anonymous "; RemotePass =" jaimon@school2000.co.uk "; RemotePort = 21; debug = false; logined = false;

}

///// set the name of the ftp server to connect to. ///// Server name public void setremotehost (string remotehost) {this.remotehost = Remotehost;}

///// Return the name of the current ftp server. ///// Server name public string getremotehost () {return remotehost;}

/// // set the port number to use for ftp. /// // port number public void setremoteport (int RemotEport) {this.remoteport = RemotEport;}

///// Return the current port number. /// // Current Port Number Public Int getRemotEport () {Return RemotEport;} ///// set the remote directory path. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Remote Directory Path Public Void SetRemotePath (String RemotePath) {this.remotepath = RemotePath;}

.

///// set the user name to use for logging in /////////////////////////////////////////////////////////////////- this.remoteuser = Remoteuser;}

///// set the password to user for logging inTo the remote server. ///// Password public void setRemotePass (String RemotePass) {this.remotepass = RemotePass;}

///// Return A String Array Containing The Remote Directory's File List. /// /// // Public String [] getFileList (String Mask) {

IF (! logined) {login ();

Socket csocket = createdataSocket ();

SendCommand ("NLST" MASK);

IF (! (RetValue == 150 || RETVALUE == 125)) {throw new oException (reply.substring (4));

MES = "";

While (true) {

Int bytes = csocket.receive (Buffer, Buffer.Length, 0); MES = ascii.getstring (buffer, 0, bytes);

IF (Bytes

Char [] seperator = {'/ n'}; string [] message = mes.split (seperator);

Csocket.close ();

ReadReply ();

IF (RetValue! = 226) {throw new oException (reply.substring (4));} Return Mess;}

///// Return the size of a file. /// / / / / / PUBLIC Long getFileSize (String filename) {

IF (! logined) {login ();

SendCommand ("size" filename); long size = 0;

IF (RetValue == 213) {size = int64.parse (reply.substring (4));} else {throw new oException (reply.substring (4));}

Return size;

}

/// // login to the remote server. /// public void login () {

ClientSocket = new socket (addressfamily.internetwork, sockettype.internem, protocoltype.tcp); IpendPoint EP = New IpendPoint (DNS.Resolve (Remotehost) .addressList [0], Remoteport);

Try {ClientSocket.connect (EP); "Catch (" "COULDN '' CONNECT to Remote Server);

ReadReply (); if (RetValue! = 220) {close (); throw new oException (reply.substring (4));} if (debug) Console.WriteLine ("User" Remoteuser;

SendCommand ("User" Remoteuser;

IF (! (RetValue == 331 || RetValue == 230)) {cleanup (); throw new oException (reply.substring (4));}

IF (RetValue! = 230) {if (debug) Console.WriteLine ("pass xxx");

Sendcommand ("Pass" RemotePass; if (! (RetValue == 230 || RetValue == 202)) {cleanup (); throw new oException (reply.substring (4));}}

Logined = true; console.writeline ("Connected to" transotehost; chDIR (RemotePath);

}

///// if the value of mode is true, set binary mode for Downloads. /// else, set ascii mode. ///// Public void setbinarymode (boolean mode) {

IF ("Type I");} else {sendcommand ("Type A");} if (RetValue! = 200) {throw new oException (reply.substring (4));}} public void download no String Remfilename) {Download (RemfileName, "", FALSE);

///// Download a Remote File to the assembly's local directory, /// Keeping The Same File Name, And Set The Resume Flag. /// ///// Public Void Download (String RemfilenaMe, Boolean ResMe) {Download (REMFILENAME, "", RESUME);

///// 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. ///// / // Public void Download (String remoteename) {Download (RemfileName, LocFileName, False);

///// 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 /// create or overwritten, but the path must exist. / BUT THE PATH MUST. / //// / / / //////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// / / / / String Loc FileName, Boolean ResMe) {if (! Logined) {login ();}

SetBinaryMode (TRUE);

Console.writeline ("Downloading File" RemfileName "from" Remotehost "/" RemotePath);

IF (LocFileName.equals (")) {locFileName = RemfileName;} if (! file.exists (locfilename)) {stream st = file.create (locFileName); st.close ();

FILESTREAM OUTPUT = New FileStream (LocFileName, FileMode.Open);

Socket csocket = createdataSocket ();

Long offset = 0;

IF (resume) {

OFFSET = OUTPUT.LENGTH;

IF (Offset> 0) {Sendcommand; if (RetValue! = 350) {// throw new oException (reply.substring (4)); // Some Servers May Not Support Resuming. Offset = 0 }}

IF (Offset> 0) {if (debug) {Console.writeline ("Seeking to" offset;} long npos = Output.seek; console.writeline ("new pos =" npos }}

SendCommand ("Retr" RemfileName;

IF (! (RetValue == 150 || RETVALUE == 125)) {throw new oException (reply.substring (4));

While (true) {

BYtes = CSocket.Receive (buffer, buffer.length, 0); Output.write (buffer, 0, bytes);

IF (Bytes <= 0) {Break;}}

Output.close (); if (csocket.Connected) {csocket.close ();

Console.writeline ("");

ReadReply ();

IF (! (r == 250)) {throw new oException (reply.substring (4));

}

///// Upload a file. ///// Public void upload (String filename) {UPLOAD (filename, false);}

///// Upload a file and set the resume flag. /////// Public void upload (String FileName, Boolean ResMe) {if (! Logined) {login ();}

Socket csocket = createdataSocket (); long offset = 0;

IF (resume) {

Try {

SetBinaryMode (TRUE); offset = getFileSize (filename);

} CatCH (exception) {offset = 0;}}

IF (Offset> 0) {SendCommand; if (RetValue! = 350) {// throw new oException (reply.substring (4)); // Remote Server May Not Support Resuming. Offset = 0 }}

Sendcommand ("stor" path.getfilename (filename));

IF (! (RetValue == 125 || RetValue == 150)) {THROW New IOException (reply.substring (4));

// Open INPUT STREAM To Read Source File FileStream Input = New FileStream (FileName, FileMode.Open);

IF (Offset! = 0) {

IF (debug) {Console.writeline ("seeking to" offset;} Input.seek (offset, seekorigin.begin);

Console.WriteLine ("UPLoading File" "To" RemotePath;

While ((Bytes = INPUT.READ (Buffer, 0, Buffer.Length)> 0) {

Csocket.send (buffer, bytes, 0);

INPUT.CLOSE ();

Console.writeline ("");

IF (csocket.Connected) {csocket.close ();

ReadReply (); if (! ((! (!) {throw new oException (reply.substring (4));}}

/// // delete a file from the remote ftp server. ///// Public void deleteremotefile (String filename) {if (! Logined) {login ();

SendCommand ("dele" filename;

IF (RetValue! = 250) {THROW New IOException (reply.substring (4));

}

///// Rename a file on the remote ftp server. //// / / / PUBLIC VOID RENAMEREMOTEFILE (STRING OLDFILENAME, STRING NewFileName) {

IF (! logined) {login ();

Sendcommand ("RNFR" OldFileName;

IF (RetValue! = 350) {throw new oException (reply.substring (4));

// known problem // rnto will not take care of existing file // ie It will overwrite if newFileName exist sendCommand ( "RNTO" newFileName);. If (! RetValue = 250) {throw new IOException (reply.Substring (4 ));

}

///// Create a Directory on the remote ftp server. ///// Public void mkdir (String Dirname) {

IF (! logined) {login ();

Sendcommand ("MKD" DIRNAME);

IF (RetValue! = 250) {THROW New IOException (reply.substring (4));

}

/// // delete a directory on the remote ftp server. ///// Public void RMDIR (String Dirname) {

IF (! logined) {login ();

Sendcommand ("RMD" DirName;

IF (RetValue! = 250) {THROW New IOException (reply.substring (4));

}

///// Change the current working directory on the remote ftp server. ///// Public void chdir (String Dirname) {

IF (Dirname.equals (")) {Return;}

IF (! logined) {login ();} Sendcommand ("CWD" DIRNAME);

IF (RetValue! = 250) {THROW New IOException (reply.substring (4));

THIS.RemotePath = DIRNAME;

Console.WriteLine ("Current Directory IS" RemotePath);

}

/// // close the ftp connection. /// public void close () {

IF (ClientSocket! = null) {Sendcommand ("quit");}

Cleanup (); console.writeline ("closing ...");}

///// SET Debug Mode. ///// Public void setdebug (boolean debug) {this.debug = debug;}

Private void readreply () {ms = ""; reply = readline (); retvalue = int32.parse (reply.substring (0,3));

Private void cleanup () {if (clientsocket! = null) {clientsocket.close (); clientsocket = null;} logined = false;

Private string readline () {

While (true) {bytes = clientsocket.Receive (buffer, buffer.length, 0); MES = ascii.getstring (buffer, 0, bytes); if (bytes

Char [] seperator = {'/ n'}; string [] message = mes.split (seperator);

IF (Mes.Length> 2) {MES = Mess [Mess.Length-2];} else {mes = mess [0];

IF (! mes.substring (3,1). Equals (")) {return readline ();}

IF (debug) {for (int K = 0; k

Private void sendcommand (String command) {

Byte [] cmdbytes = encoding.ascii.getbytes ((Command "/ R / N"); Tochararray ()); ClientSocket.send (cmdbytes, cmdbytes.length, 0); readReply ();} private socket createdataSocket () {

Sendcommand ("PASV");

IF (RetValue! = 227) {throw new oException (reply.substring (4));

INDEX1 = reply.indexof ('); int index2 = reply.indexof (') '); string ipdata = reply.substring (index1 1, index2-index1-1); int [] parts = new int = 6];

INT LEN = ipdata.length; int partictcount = 0; string buf = "";

For (int i = 0; i

CHAR CH = Char.Parse (IPData.Substring (i, 1)); if (Char.Indigit (CH)) BUF = CH; ELSE IF (CH! = ',') {Throw new oException ("Malformed Pasv reply) " reply);

IF (CH == ',' || i 1 == LEN) {

Try {parts [partcount ] = int32.parse (buf); buf = "";} catch ("{throw new oException (" Malformed Pasv reply: " reply);}}}

String ipaddress = parts [0] "." Parts [1] "." Parts [2] "." Parts [3];

INT port = (Parts [4] << 8) Parts [5];

Socket s = new socket (addressFamily.internetwork, sockettype.internem, protocoltype.tcp); IpendPoint EP = New IpendPoint (DNS.Resolve (ipaddress) .addresslist [0], port);

Try {s.connect (EP); (Exception) {throw new oException ("can't connect to remote server);} Return S;

}

test:

Using system; using ftplib;

Public class test {

Public static void main () {

Try {

Console.writeline ("Starting ...");

FTPFactory ff = new ftpFactory (); ff.setdebug (true); ff.setRemotehost ("10.138.7.169"); ff.setRemoteuser ("SBD"); ff.setRemotePass ("sbd"); ff.login (); ff.chdir ("test");

String [] filenames = ff.getFileList ("*. *"); for (int i = 0; i

Ff.setBinaryMode (true); ff.upload ("c: //sample1.xml"); ff.close ();

} Catch (Exception E) {Console.writeLine ("Caught Error:" E.MESSAGE);}}}}}}

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

New Post(0)