C#版ftp方法实现类的代码
C#版ftp方法实现类的代码
发布时间:2016-12-28 来源:查字典编辑
摘要:/*FTPFactory.csBetterviewwithtabspace=4WrittenbyJaimonMathew(jaimonmat...

/*

FTPFactory.cs

Betterviewwithtabspace=4

WrittenbyJaimonMathew(jaimonmathew@rediffmail.com)

Rolander,Dan(Dan.Rolander@marriott.com)hasmodifiedthe

download

methodtocopewithfilenamewithpathinformation.Healso

provided

theXMLcommentssothatthelibraryprovidesIntellisense

descriptions.

usethefollowinglinetocompile

csc/target:library/out:FTPLib.dll/r:System.DLLFTPFactory.cs

*/

usingSystem;

usingSystem.Threading;

usingSystem.Net;

usingSystem.IO;

usingSystem.Text;

usingSystem.Net.Sockets;

usingSystem.Configuration;

namespaceAudioCollect

{

///<summary>

///FTPFactory的摘要说明。

///</summary>

publicclassFTPFactory

{

staticreadonlylog4net.ILoglog=log4net.LogManager.GetLogger("log4net");

privatestring

remoteHost,remotePath,remoteUser,remotePass,mes;

privateintremotePort,bytes;

privateSocketclientSocket;

privateintretValue;

privateBooleandebug;

privateBooleanlogined;

privatestringreply;

privatestaticintBLOCK_SIZE=512;

Byte[]buffer=newByte[BLOCK_SIZE];

EncodingASCII=Encoding.ASCII;

publicFTPFactory()

{

stringFTPRemoteIP=ConfigurationSettings.AppSettings["FTPRemoteIP"];

intFTPRemotePort=Convert.ToInt32(ConfigurationSettings.AppSettings["FTPRemotePort"]);

stringFTPUser=ConfigurationSettings.AppSettings["FTPUser"];

stringFTPPassword=ConfigurationSettings.AppSettings["FTPPassword"];

remoteHost=FTPRemoteIP;

remotePath=".";

remoteUser=FTPUser;

remotePass=FTPPassword;

remotePort=FTPRemotePort;

debug=false;

logined=false;

}

///

///SetthenameoftheFTPservertoconnectto.

///

///Servername

publicvoidsetRemoteHost(stringremoteHost)

{

this.remoteHost=remoteHost;

}

///

///ReturnthenameofthecurrentFTPserver.

///

///Servername

publicstringgetRemoteHost()

{

returnremoteHost;

}

///

///SettheportnumbertouseforFTP.

///

///Portnumber

publicvoidsetRemotePort(intremotePort)

{

this.remotePort=remotePort;

}

///

///Returnthecurrentportnumber.

///

///Currentportnumber

publicintgetRemotePort()

{

returnremotePort;

}

///

///Settheremotedirectorypath.

///

///Theremotedirectorypath

publicvoidsetRemotePath(stringremotePath)

{

this.remotePath=remotePath;

}

///

///Returnthecurrentremotedirectorypath.

///

///Thecurrentremotedirectorypath.

publicstringgetRemotePath()

{

returnremotePath;

}

///

///Settheusernametouseforloggingintotheremoteserver.

///

///Username

publicvoidsetRemoteUser(stringremoteUser)

{

this.remoteUser=remoteUser;

}

///

///Setthepasswordtouserforloggingintotheremoteserver.

///

///Password

publicvoidsetRemotePass(stringremotePass)

{

this.remotePass=remotePass;

}

///

///Returnastringarraycontainingtheremotedirectory'sfilelist.

///

///

///

publicstring[]getFileList(stringmask)

{

if(!logined)

{

login();

}

SocketcSocket=createDataSocket();

sendCommand("NLST"+mask);

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

{

thrownewIOException(reply.Substring(4));

}

mes="";

Thread.Sleep(700);

while(true)

{

if(cSocket.Connected)

{

intbytes=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(stringfileNameinmess)

{

log.Info(fileName);

}

cSocket.Close();

readReply();

if(retValue!=226)

{

thrownewIOException(reply.Substring(4));

}

returnmess;

}

publicstring[]getFileList()

{

if(!logined)

{

login();

}

SocketcSocket=createDataSocket();

sendCommand("LIST");

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

{

thrownewIOException(reply.Substring(4));

}

mes="";

while(true)

{

intbytes=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)

{

thrownewIOException(reply.Substring(4));

}

returnmess;

}

///

///Returnthesizeofafile.

///

///

///

publiclonggetFileSize(stringfileName)

{

if(!logined)

{

login();

}

sendCommand("SIZE"+fileName);

longsize=0;

if(retValue==213)

{

size=Int64.Parse(reply.Substring(4));

}

else

{

thrownewIOException(reply.Substring(4));

}

returnsize;

}

///

///Logintotheremoteserver.

///

publicvoidlogin()

{

clientSocket=new

Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

IPEndPointep=new

IPEndPoint(Dns.Resolve(remoteHost).AddressList[0],remotePort);

try

{

clientSocket.Connect(ep);

}

catch(Exception)

{

thrownewIOException("Couldn'tconnecttoremoteserver");

}

readReply();

if(retValue!=220)

{

close();

thrownewIOException(reply.Substring(4));

}

if(debug)

Console.WriteLine("USER"+remoteUser);

sendCommand("USER"+remoteUser);

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

{

cleanup();

thrownewIOException(reply.Substring(4));

}

if(retValue!=230)

{

if(debug)

Console.WriteLine("PASSxxx");

sendCommand("PASS"+remotePass);

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

{

cleanup();

thrownewIOException(reply.Substring(4));

}

}

logined=true;

Console.WriteLine("Connectedto"+remoteHost);

chdir(remotePath);

}

///

///Ifthevalueofmodeistrue,setbinarymodefordownloads.

///Else,setAsciimode.

///

///

publicvoidsetBinaryMode(Booleanmode)

{

if(mode)

{

sendCommand("TYPEI");

}

else

{

sendCommand("TYPEA");

}

if(retValue!=200)

{

thrownewIOException(reply.Substring(4));

}

}

///

///DownloadafiletotheAssembly'slocaldirectory,

///keepingthesamefilename.

///

///

publicvoiddownload(stringremFileName)

{

download(remFileName,"",false);

}

///

///DownloadaremotefiletotheAssembly'slocaldirectory,

///keepingthesamefilename,andsettheresumeflag.

///

///

///

publicvoiddownload(stringremFileName,Booleanresume)

{

download(remFileName,"",resume);

}

///

///Downloadaremotefiletoalocalfilenamewhichcaninclude

///apath.Thelocalfilenamewillbecreatedoroverwritten,

///butthepathmustexist.

///

///

///

publicvoiddownload(stringremFileName,stringlocFileName)

{

download(remFileName,locFileName,false);

}

///

///Downloadaremotefiletoalocalfilenamewhichcaninclude

///apath,andsettheresumeflag.Thelocalfilenamewillbe

///createdoroverwritten,butthepathmustexist.

///

///

///

///

publicvoiddownload(stringremFileName,string

locFileName,Booleanresume)

{

if(!logined)

{

login();

}

setBinaryMode(false);

Console.WriteLine("Downloadingfile"+remFileName+"from"+remoteHost+"//"+remotePath);

if(locFileName.Equals(""))

{

locFileName=remFileName;

}

if(!File.Exists(locFileName))

{

Streamst=File.Create(locFileName);

st.Close();

}

FileStreamoutput=new

FileStream(locFileName,FileMode.Create);

SocketcSocket=createDataSocket();

longoffset=0;

if(resume)

{

offset=output.Length;

if(offset>0)

{

setBinaryMode(false);

sendCommand("REST"+offset);

if(retValue!=350)

{

//thrownewIOException(reply.Substring(4));

//Someserversmaynotsupportresuming.

offset=0;

}

}

if(offset>0)

{

if(debug)

{

Console.WriteLine("seekingto"+offset);

}

longnpos=output.Seek(offset,SeekOrigin.Begin);

Console.WriteLine("newpos="+npos);

}

}

sendCommand("RETR"+remFileName);

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

{

thrownewIOException(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))

{

thrownewIOException(reply.Substring(4));

}

}

///

///Uploadafile.

///

///

publicvoidupload(stringfileName)

{

upload(fileName,false);

}

///

///Uploadafileandsettheresumeflag.

///

///

///

publicvoidupload(stringfileName,Booleanresume)

{

if(!logined)

{

login();

}

SocketcSocket=createDataSocket();

longoffset=0;

if(resume)

{

try

{

setBinaryMode(true);

offset=getFileSize(fileName);

}

catch(Exception)

{

offset=0;

}

}

if(offset>0)

{

sendCommand("REST"+offset);

if(retValue!=350)

{

//thrownewIOException(reply.Substring(4));

//Remoteservermaynotsupportresuming.

offset=0;

}

}

/*==========================*/

sendCommand("STOR"+Path.GetFileName(fileName));

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

{

thrownewIOException(reply.Substring(4));

}

//openinputstreamtoreadsourcefile

FileStreaminput=newFileStream(fileName,FileMode.Open);

if(offset!=0)

{

if(debug)

{

Console.WriteLine("seekingto"+offset);

}

input.Seek(offset,SeekOrigin.Begin);

}

Console.WriteLine("Uploadingfile"+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))

{

thrownewIOException(reply.Substring(4));

}

}

///

///DeleteafilefromtheremoteFTPserver.

///

///

publicvoiddeleteRemoteFile(stringfileName)

{

if(!logined)

{

login();

}

sendCommand("DELE"+fileName);

if(retValue!=250)

{

thrownewIOException(reply.Substring(4));

}

}

///

///RenameafileontheremoteFTPserver.

///

///

///

publicvoidrenameRemoteFile(stringoldFileName,string

newFileName)

{

if(!logined)

{

login();

}

sendCommand("RNFR"+oldFileName);

if(retValue!=350)

{

thrownewIOException(reply.Substring(4));

}

//knownproblem

//rntowillnottakecareofexistingfile.

//i.e.ItwilloverwriteifnewFileNameexist

sendCommand("RNTO"+newFileName);

if(retValue!=250)

{

thrownewIOException(reply.Substring(4));

}

}

///

///CreateadirectoryontheremoteFTPserver.

///

///

publicvoidmkdir(stringdirName)

{

if(!logined)

{

login();

}

sendCommand("MKD"+dirName);

if(retValue!=250)

{

thrownewIOException(reply.Substring(4));

}

}

///

///DeleteadirectoryontheremoteFTPserver.

///

///

publicvoidrmdir(stringdirName)

{

if(!logined)

{

login();

}

sendCommand("RMD"+dirName);

if(retValue!=250)

{

thrownewIOException(reply.Substring(4));

}

}

///

///ChangethecurrentworkingdirectoryontheremoteFTPserver.

///

///

publicvoidchdir(stringdirName)

{

if(dirName.Equals("."))

{

return;

}

if(!logined)

{

login();

}

sendCommand("CWD"+dirName);

if(retValue!=250)

{

thrownewIOException(reply.Substring(4));

}

this.remotePath=dirName;

Console.WriteLine("Currentdirectoryis"+remotePath);

}

///

///ClosetheFTPconnection.

///

publicvoidclose()

{

if(clientSocket!=null)

{

sendCommand("QUIT");

}

cleanup();

Console.WriteLine("Closing...");

}

///

///Setdebugmode.

///

///

publicvoidsetDebug(Booleandebug)

{

this.debug=debug;

}

privatevoidreadReply()

{

mes="";

reply=readLine();

retValue=Int32.Parse(reply.Substring(0,3));

}

privatevoidcleanup()

{

if(clientSocket!=null)

{

clientSocket.Close();

clientSocket=null;

}

logined=false;

}

privatestringreadLine()

{

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(""))

{

returnreadLine();

}

if(debug)

{

for(intk=0;k<mess.Length-1;k++)

{

Console.WriteLine(mess[k]);

}

}

returnmes;

}

privatevoidsendCommand(Stringcommand)

{

Byte[]cmdBytes=

Encoding.ASCII.GetBytes((command+"rn").ToCharArray());

clientSocket.Send(cmdBytes,cmdBytes.Length,0);

readReply();

}

privateSocketcreateDataSocket()

{

sendCommand("PASV");

if(retValue!=227)

{

thrownewIOException(reply.Substring(4));

}

intindex1=reply.IndexOf('(');

intindex2=reply.IndexOf(')');

stringipData=

reply.Substring(index1+1,index2-index1-1);

int[]parts=newint[6];

intlen=ipData.Length;

intpartCount=0;

stringbuf="";

for(inti=0;i<len&&partCount<=6;i++)

{

charch=Char.Parse(ipData.Substring(i,1));

if(Char.IsDigit(ch))

buf+=ch;

elseif(ch!=',')

{

thrownewIOException("MalformedPASVreply:"+

reply);

}

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

{

try

{

parts[partCount++]=Int32.Parse(buf);

buf="";

}

catch(Exception)

{

thrownewIOException("MalformedPASVreply:"+

reply);

}

}

}

stringipAddress=parts[0]+"."+parts[1]+"."+

parts[2]+"."+parts[3];

intport=(parts[4]<<8)+parts[5];

Sockets=new

Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

s.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.SendTimeout,5000);

IPEndPointep=new

IPEndPoint(Dns.Resolve(ipAddress).AddressList[0],port);

try

{

s.Connect(ep);

}

catch(Exception)

{

thrownewIOException("Can'tconnecttoremoteserver");

}

returns;

}

}

}

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新C#教程学习
热门C#教程学习
编程开发子分类