C # version FTP method implementation class library code

xiaoxiao2021-03-06  40

Recently, I have to be a MP3 search, and automatically upload the program uploaded. I found a class library that found this FTP method was good, and sent them to everyone. Share. / *

FtpFactory.cs

Better View with Tab Space = 4

Written by jaimon mathew (jaimonmathew@rediffmail.com)

Rolander, Dan (Dan.Rolaander@marriott.com) HAS MODIFIED THE

Download

Method to Cope with File Name with path information. He Also

provided

The XML Comments So That The Library Provides IntelliSense

Descriptions.

Use the folowing line to compile

CSC / Target: library /out:ftplib.dll /r:system.dll ftpFactory.cs

* /

Using system;

Using system.threading;

Using system.net;

Using system.io;

Using system.text;

Using system.net.sockets;

Using system.configuration;

Namespace Audiocollect

{

///

/// ftpFactory's summary description.

///

Public class ftpFactory

{

Static Readonly log4net.ilog log = log4net.logmanager.getlogger ("log4net");

Private string

Remotehost, RemotePath, Remoteuser, RemotePass, MES;

Private int RemotEport, Bytes;

Private socket clientsocket;

Private int RetValue;

PRIVATE BOOLEAN DEBUG;

Private boolean logined;

PRIVATE STRING Reply;

Private static int block_size = 512;

Byte [] buffer = new byte [block_size];

ENCODING ASCII = Encoding.ASCII;

Public ftpFactory ()

{

String ftpRemoteip = configurationSettings.appsettings ["ftpremoteip"];

INT ftpRemotEport = Convert.Toint32 (ConfigurationSettings.AppSettings ["ftpRemotEport"]);

String ftpuser = configurationSettings.appsettings ["ftpuser"];

String ftppassword = configurationSettings.appsettings ["ftppassword"];

Remotehost = ftpRemoteip;

RemotePath = "."

Remoteuser = ftpuser;

Remotepass = ftppassword;

RemotEport = ftpRemotEport;

Debug = false;

Logined = false;

}

///

/// set the name of the ftp server to connect.

///

/// server name

Public void setRemotehost (String Remotehost)

{

THIS.Remotehost = Remotehost;

}

///

/// Return the name of the capital 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.

///

/// The Remote Directory Path

Public void setRemotePath (String RemotePath)

{

THIS.RemotePath = RemotePath;

}

///

/// Return The Current Remote Directory Path.

///

/// The Current Remote Directory Path.

Public string getRemotePath ()

{

Return RemotePath;

}

///

/// set the user name to use for logging INTO The Remote Server.

///

/// username

Public void setRemoteuser (String Remoteuser)

{

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 = "";

Thread.sleep (700);

While (True)

{

IF (csocket.connected)

{

Int bytes = csocket.Receive (buffer, buffer.length, 0);

Mes = ascii.getstring (buffer, 0, bytes);

IF (Bytes

{

Break;

}

}

Else

{

Log.info ("Socket connection is broken!");

}

}

Log.info (MES);

Char [] seperator = {'/ n'};

String [] message = mes.split (seperator);

FOREACH (String FileName In Mess)

{

Log.info (filename);

}

Csocket.close ();

ReadReply ();

IF (RetValue! = 226)

{

Throw new oException (reply.substring (4));

}

Return Mess;

}

Public string [] getFileList ()

{

IF (! logined)

{

Login ();

}

Socket csocket = createdataSocket ();

Sendcommand ("List");

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

{

Break;

}

}

Log.info (MES);

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.Stream, protocoltype.tcp);

IpendPoint EP = New

IpendPoint (DNS.Resolve (Remotehost) .addresslist [0], Remoteport); TRY

{

Clientsocket.connect (EP);

}

Catch (Exception)

{

Throw New IOException ("COULDN't 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" Remotehost;

CHDIR (RemotePath);

}

///

/// if the value of mode is true, set binary model for downloads.

/// else, set ascii mode.

///

///

Public void setBinaryMode (Boolean Mode)

{

IF (Mode)

{

SendCommand ("Type I");

}

Else

{

SendCommand ("Type A");

}

IF (RetValue! = 200)

{

Throw new oException (reply.substring (4));

}

}

///

/// Download a File to the assembly's local directory,

/// Keeping The Same File Name.

///

///

Public void Download (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 Resume)

{

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 RemfileName, String Locfilename)

{

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

/// Created or OverWritten, but the path must exist.

///

///

///

///

Public void Download (String Remfilename, String

LocFileName, Boolean ResMe

{

IF (! logined)

{

Login ();

}

SetBinaryMode (false);

Console.Writeline ("Downloading File" RemoteHost "//" RemotePath);

IF (LocFileName.equals ("))

{

LocFileName = RemfileName;

}

IF (! file.exists (locfilename))

{

Street st = file.create (locFilename);

St.close ();

}

FILESTREAM OUTPUT = New

FileStream (LocFileName, FileMode.create);

Socket csocket = createdataSocket ();

Long offset = 0;

IF (resume)

{

OFFSET = OUTPUT.LENGTH;

IF (Offset> 0)

{

SetBinaryMode (false);

SendCommand ("REST" offset);

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 (offset, seekorigin.begin);

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 (! (RetValue == 226 || RetValue == 250))))

{

Throw new oException (reply.substring (4));

}

}

///

/// Upload a file.

///

///

Public void Upload (String FileName)

{

Upload (FileName, False);

}

///

/// Upload a file and set the resme flag.

///

///

///

Public void Upload (String Filename, Boolean Resume)

{

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 ("REST" offset);

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 oException (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 (! (RetValue == 226 || RetValue == 250))))

{

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 oException (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.

// I. IT Will Overwrite if newFileName EXIST

Sendcommand ("RNTO NewFileName);

IF (RetValue! = 250)

{

Throw new oException (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 oException (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 oException (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 oException (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 ()

{

MES = "";

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

{

Break;

}

}

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

{

Console.writeLine (Mess [k]);

}

}

Return Mes;

}

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 Partcount = 0;

String buf = "";

For (int i = 0; i

{

Char ch = char.parse (iPdata.Substring (i, 1));

CHAR.ISDIGIT (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 (Exception)

{

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.Stream, protocoltype.tcp);

S.SetSocketoption (socketoptionlevel.socket, socketoptionname.sendtimeout, 5000);

IpendPoint EP = New

IpendPoint (DNS.Resolve (ipaddress) .addresslist [0], port);

Try

{

S.Connect (EP);

}

Catch (Exception)

{

Throw new oException ("Can't Connect To Remote Server);

}

Return S;

}

}

}

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

New Post(0)