首页 > 开发 > 综合 > 正文

C#版ftp方法实现类库代码

2024-07-21 02:18:04
字体:
来源:转载
供稿:网友
最近要做个mp3搜索,并自动ftp上传的程序,找来找去发现了这个ftp方法的类库不错,发上来给大家共享共享。
/*

ftpfactory.cs

better view with tab space=4



written by jaimon mathew ([email protected])

rolander,dan ([email protected]) 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 following 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

{

/// <summary>

/// ftpfactory 的摘要说明。

/// </summary>

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

///

/// 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 ioexception(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 < buffer.length)

{

break;

}

}

else

{

log.info("socket 连接断了!");

}

}

log.info(mes);

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

string[] mess = mes.split(seperator);

foreach(string filename in mess)

{

log.info(filename);

}

csocket.close();



readreply();



if(retvalue != 226)

{

throw new ioexception(reply.substring(4));

}

return mess;



}

public string[] getfilelist()

{

if(!logined)

{

login();

}



socket csocket = createdatasocket();



sendcommand("list ");



if(!(retvalue == 150 || retvalue == 125))

{

throw new ioexception(reply.substring(4));

}



mes = "";



while(true)

{



int bytes = csocket.receive(buffer, buffer.length, 0);

mes += ascii.getstring(buffer, 0, bytes);



if(bytes < buffer.length)

{

break;

}

}



log.info(mes);

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

string[] mess = mes.split(seperator);



csocket.close();



readreply();



if(retvalue != 226)

{

throw new ioexception(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 ioexception(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 ioexception(reply.substring(4));

}

if(debug)

console.writeline("user "+remoteuser);



sendcommand("user "+remoteuser);



if( !(retvalue == 331 || retvalue == 230) )

{

cleanup();

throw new ioexception(reply.substring(4));

}



if( retvalue != 230 )

{

if(debug)

console.writeline("pass xxx");



sendcommand("pass "+remotepass);

if( !(retvalue == 230 || retvalue == 202) )

{

cleanup();

throw new ioexception(reply.substring(4));

}

}



logined = true;

console.writeline("connected to "+remotehost);



chdir(remotepath);



}



///

/// if the value of mode is true, set binary mode 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 ioexception(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 resume)

{

if(!logined)

{

login();

}



setbinarymode(false);



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.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 ioexception(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 ioexception(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 ioexception(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 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 ioexception(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 "+filename+" 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 ioexception(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 ioexception(reply.substring(4));

}



// known problem

// rnto will not take care of existing file.

// i.e. 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()

{

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 < buffer.length)

{

break;

}

}



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

string[] mess = 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 < mess.length-1;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 ioexception(reply.substring(4));

}



int 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 < len && partcount <= 6; i++)

{



char ch = char.parse(ipdata.substring(i,1));

if (char.isdigit(ch))

buf+=ch;

else if (ch != ',')

{

throw new ioexception("malformed pasv reply: " +

reply);

}



if (ch == ',' || i+1 == len)

{



try

{

parts[partcount++] = int32.parse(buf);

buf="";

}

catch (exception)

{

throw new ioexception("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 ioexception("can't connect to remote server");

}



return s;

}



}

}


最大的网站源码资源下载站,

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表