分享用于操作FTP的客户端C#类
这是一个用于操作FTP的客户端C#类,类已经封装好了各种常用的Ftp操作方法,调用非常简单,你不需要关心ftp连接和操作的细节,只要调用这个类里的相关方法就可以了。
usingSystem; usingSystem.Net; usingSystem.IO; usingSystem.Text; usingSystem.Net.Sockets; usingSystem.Threading; namespaceDotNet.Utilities { publicclassFTPClient { publicstaticobjectobj=newobject(); #region构造函数 ///<summary> ///缺省构造函数 ///</summary> publicFTPClient() { strRemoteHost=""; strRemotePath=""; strRemoteUser=""; strRemotePass=""; strRemotePort=21; bConnected=false; } ///<summary> ///构造函数 ///</summary> publicFTPClient(stringremoteHost,stringremotePath,stringremoteUser,stringremotePass,intremotePort) { strRemoteHost=remoteHost; strRemotePath=remotePath; strRemoteUser=remoteUser; strRemotePass=remotePass; strRemotePort=remotePort; Connect(); } #endregion #region字段 privateintstrRemotePort; privateBooleanbConnected; privatestringstrRemoteHost; privatestringstrRemotePass; privatestringstrRemoteUser; privatestringstrRemotePath; ///<summary> ///服务器返回的应答信息(包含应答码) ///</summary> privatestringstrMsg; ///<summary> ///服务器返回的应答信息(包含应答码) ///</summary> privatestringstrReply; ///<summary> ///服务器返回的应答码 ///</summary> privateintiReplyCode; ///<summary> ///进行控制连接的socket ///</summary> privateSocketsocketControl; ///<summary> ///传输模式 ///</summary> privateTransferTypetrType; ///<summary> ///接收和发送数据的缓冲区 ///</summary> privatestaticintBLOCK_SIZE=512; ///<summary> ///编码方式 ///</summary> EncodingASCII=Encoding.ASCII; ///<summary> ///字节数组 ///</summary> Byte[]buffer=newByte[BLOCK_SIZE]; #endregion #region属性 ///<summary> ///FTP服务器IP地址 ///</summary> publicstringRemoteHost { get { returnstrRemoteHost; } set { strRemoteHost=value; } } ///<summary> ///FTP服务器端口 ///</summary> publicintRemotePort { get { returnstrRemotePort; } set { strRemotePort=value; } } ///<summary> ///当前服务器目录 ///</summary> publicstringRemotePath { get { returnstrRemotePath; } set { strRemotePath=value; } } ///<summary> ///登录用户账号 ///</summary> publicstringRemoteUser { set { strRemoteUser=value; } } ///<summary> ///用户登录密码 ///</summary> publicstringRemotePass { set { strRemotePass=value; } } ///<summary> ///是否登录 ///</summary> publicboolConnected { get { returnbConnected; } } #endregion #region链接 ///<summary> ///建立连接 ///</summary> publicvoidConnect() { lock(obj) { socketControl=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); IPEndPointep=newIPEndPoint(IPAddress.Parse(RemoteHost),strRemotePort); try { socketControl.Connect(ep); } catch(Exception) { thrownewIOException("不能连接ftp服务器"); } } ReadReply(); if(iReplyCode!=220) { DisConnect(); thrownewIOException(strReply.Substring(4)); } SendCommand("USER"+strRemoteUser); if(!(iReplyCode==331||iReplyCode==230)) { CloseSocketConnect(); thrownewIOException(strReply.Substring(4)); } if(iReplyCode!=230) { SendCommand("PASS"+strRemotePass); if(!(iReplyCode==230||iReplyCode==202)) { CloseSocketConnect(); thrownewIOException(strReply.Substring(4)); } } bConnected=true; ChDir(strRemotePath); } ///<summary> ///关闭连接 ///</summary> publicvoidDisConnect() { if(socketControl!=null) { SendCommand("QUIT"); } CloseSocketConnect(); } #endregion #region传输模式 ///<summary> ///传输模式:二进制类型、ASCII类型 ///</summary> publicenumTransferType{Binary,ASCII}; ///<summary> ///设置传输模式 ///</summary> ///<paramname="ttType">传输模式</param> publicvoidSetTransferType(TransferTypettType) { if(ttType==TransferType.Binary) { SendCommand("TYPEI");//binary类型传输 } else { SendCommand("TYPEA");//ASCII类型传输 } if(iReplyCode!=200) { thrownewIOException(strReply.Substring(4)); } else { trType=ttType; } } ///<summary> ///获得传输模式 ///</summary> ///<returns>传输模式</returns> publicTransferTypeGetTransferType() { returntrType; } #endregion #region文件操作 ///<summary> ///获得文件列表 ///</summary> ///<paramname="strMask">文件名的匹配字符串</param> publicstring[]Dir(stringstrMask) { if(!bConnected) { Connect(); } SocketsocketData=CreateDataSocket(); SendCommand("NLST"+strMask); if(!(iReplyCode==150||iReplyCode==125||iReplyCode==226)) { thrownewIOException(strReply.Substring(4)); } strMsg=""; Thread.Sleep(2000); while(true) { intiBytes=socketData.Receive(buffer,buffer.Length,0); strMsg+=ASCII.GetString(buffer,0,iBytes); if(iBytes<buffer.Length) { break; } } char[]seperator={'\n'}; string[]strsFileList=strMsg.Split(seperator); socketData.Close();//数据socket关闭时也会有返回码 if(iReplyCode!=226) { ReadReply(); if(iReplyCode!=226) { thrownewIOException(strReply.Substring(4)); } } returnstrsFileList; } publicvoidnewPutByGuid(stringstrFileName,stringstrGuid) { if(!bConnected) { Connect(); } stringstr=strFileName.Substring(0,strFileName.LastIndexOf("\\")); stringstrTypeName=strFileName.Substring(strFileName.LastIndexOf(".")); strGuid=str+"\\"+strGuid; SocketsocketData=CreateDataSocket(); SendCommand("STOR"+Path.GetFileName(strGuid)); if(!(iReplyCode==125||iReplyCode==150)) { thrownewIOException(strReply.Substring(4)); } FileStreaminput=newFileStream(strGuid,FileMode.Open); input.Flush(); intiBytes=0; while((iBytes=input.Read(buffer,0,buffer.Length))>0) { socketData.Send(buffer,iBytes,0); } input.Close(); if(socketData.Connected) { socketData.Close(); } if(!(iReplyCode==226||iReplyCode==250)) { ReadReply(); if(!(iReplyCode==226||iReplyCode==250)) { thrownewIOException(strReply.Substring(4)); } } } ///<summary> ///获取文件大小 ///</summary> ///<paramname="strFileName">文件名</param> ///<returns>文件大小</returns> publiclongGetFileSize(stringstrFileName) { if(!bConnected) { Connect(); } SendCommand("SIZE"+Path.GetFileName(strFileName)); longlSize=0; if(iReplyCode==213) { lSize=Int64.Parse(strReply.Substring(4)); } else { thrownewIOException(strReply.Substring(4)); } returnlSize; } ///<summary> ///获取文件信息 ///</summary> ///<paramname="strFileName">文件名</param> ///<returns>文件大小</returns> publicstringGetFileInfo(stringstrFileName) { if(!bConnected) { Connect(); } SocketsocketData=CreateDataSocket(); SendCommand("LIST"+strFileName); stringstrResult=""; if(!(iReplyCode==150||iReplyCode==125 ||iReplyCode==226||iReplyCode==250)) { thrownewIOException(strReply.Substring(4)); } byte[]b=newbyte[512]; MemoryStreamms=newMemoryStream(); while(true) { intiBytes=socketData.Receive(b,b.Length,0); ms.Write(b,0,iBytes); if(iBytes<=0) { break; } } byte[]bt=ms.GetBuffer(); strResult=System.Text.Encoding.ASCII.GetString(bt); ms.Close(); returnstrResult; } ///<summary> ///删除 ///</summary> ///<paramname="strFileName">待删除文件名</param> publicvoidDelete(stringstrFileName) { if(!bConnected) { Connect(); } SendCommand("DELE"+strFileName); if(iReplyCode!=250) { thrownewIOException(strReply.Substring(4)); } } ///<summary> ///重命名(如果新文件名与已有文件重名,将覆盖已有文件) ///</summary> ///<paramname="strOldFileName">旧文件名</param> ///<paramname="strNewFileName">新文件名</param> publicvoidRename(stringstrOldFileName,stringstrNewFileName) { if(!bConnected) { Connect(); } SendCommand("RNFR"+strOldFileName); if(iReplyCode!=350) { thrownewIOException(strReply.Substring(4)); } //如果新文件名与原有文件重名,将覆盖原有文件 SendCommand("RNTO"+strNewFileName); if(iReplyCode!=250) { thrownewIOException(strReply.Substring(4)); } } #endregion #region上传和下载 ///<summary> ///下载一批文件 ///</summary> ///<paramname="strFileNameMask">文件名的匹配字符串</param> ///<paramname="strFolder">本地目录(不得以\结束)</param> publicvoidGet(stringstrFileNameMask,stringstrFolder) { if(!bConnected) { Connect(); } string[]strFiles=Dir(strFileNameMask); foreach(stringstrFileinstrFiles) { if(!strFile.Equals(""))//一般来说strFiles的最后一个元素可能是空字符串 { Get(strFile,strFolder,strFile); } } } ///<summary> ///下载一个文件 ///</summary> ///<paramname="strRemoteFileName">要下载的文件名</param> ///<paramname="strFolder">本地目录(不得以\结束)</param> ///<paramname="strLocalFileName">保存在本地时的文件名</param> publicvoidGet(stringstrRemoteFileName,stringstrFolder,stringstrLocalFileName) { SocketsocketData=CreateDataSocket(); try { if(!bConnected) { Connect(); } SetTransferType(TransferType.Binary); if(strLocalFileName.Equals("")) { strLocalFileName=strRemoteFileName; } SendCommand("RETR"+strRemoteFileName); if(!(iReplyCode==150||iReplyCode==125||iReplyCode==226||iReplyCode==250)) { thrownewIOException(strReply.Substring(4)); } FileStreamoutput=newFileStream(strFolder+"\\"+strLocalFileName,FileMode.Create); while(true) { intiBytes=socketData.Receive(buffer,buffer.Length,0); output.Write(buffer,0,iBytes); if(iBytes<=0) { break; } } output.Close(); if(socketData.Connected) { socketData.Close(); } if(!(iReplyCode==226||iReplyCode==250)) { ReadReply(); if(!(iReplyCode==226||iReplyCode==250)) { thrownewIOException(strReply.Substring(4)); } } } catch { socketData.Close(); socketData=null; socketControl.Close(); bConnected=false; socketControl=null; } } ///<summary> ///下载一个文件 ///</summary> ///<paramname="strRemoteFileName">要下载的文件名</param> ///<paramname="strFolder">本地目录(不得以\结束)</param> ///<paramname="strLocalFileName">保存在本地时的文件名</param> publicvoidGetNoBinary(stringstrRemoteFileName,stringstrFolder,stringstrLocalFileName) { if(!bConnected) { Connect(); } if(strLocalFileName.Equals("")) { strLocalFileName=strRemoteFileName; } SocketsocketData=CreateDataSocket(); SendCommand("RETR"+strRemoteFileName); if(!(iReplyCode==150||iReplyCode==125||iReplyCode==226||iReplyCode==250)) { thrownewIOException(strReply.Substring(4)); } FileStreamoutput=newFileStream(strFolder+"\\"+strLocalFileName,FileMode.Create); while(true) { intiBytes=socketData.Receive(buffer,buffer.Length,0); output.Write(buffer,0,iBytes); if(iBytes<=0) { break; } } output.Close(); if(socketData.Connected) { socketData.Close(); } if(!(iReplyCode==226||iReplyCode==250)) { ReadReply(); if(!(iReplyCode==226||iReplyCode==250)) { thrownewIOException(strReply.Substring(4)); } } } ///<summary> ///上传一批文件 ///</summary> ///<paramname="strFolder">本地目录(不得以\结束)</param> ///<paramname="strFileNameMask">文件名匹配字符(可以包含*和?)</param> publicvoidPut(stringstrFolder,stringstrFileNameMask) { string[]strFiles=Directory.GetFiles(strFolder,strFileNameMask); foreach(stringstrFileinstrFiles) { Put(strFile); } } ///<summary> ///上传一个文件 ///</summary> ///<paramname="strFileName">本地文件名</param> publicvoidPut(stringstrFileName) { if(!bConnected) { Connect(); } SocketsocketData=CreateDataSocket(); if(Path.GetExtension(strFileName)=="") SendCommand("STOR"+Path.GetFileNameWithoutExtension(strFileName)); else SendCommand("STOR"+Path.GetFileName(strFileName)); if(!(iReplyCode==125||iReplyCode==150)) { thrownewIOException(strReply.Substring(4)); } FileStreaminput=newFileStream(strFileName,FileMode.Open); intiBytes=0; while((iBytes=input.Read(buffer,0,buffer.Length))>0) { socketData.Send(buffer,iBytes,0); } input.Close(); if(socketData.Connected) { socketData.Close(); } if(!(iReplyCode==226||iReplyCode==250)) { ReadReply(); if(!(iReplyCode==226||iReplyCode==250)) { thrownewIOException(strReply.Substring(4)); } } } ///<summary> ///上传一个文件 ///</summary> ///<paramname="strFileName">本地文件名</param> publicvoidPutByGuid(stringstrFileName,stringstrGuid) { if(!bConnected) { Connect(); } stringstr=strFileName.Substring(0,strFileName.LastIndexOf("\\")); stringstrTypeName=strFileName.Substring(strFileName.LastIndexOf(".")); strGuid=str+"\\"+strGuid; System.IO.File.Copy(strFileName,strGuid); System.IO.File.SetAttributes(strGuid,System.IO.FileAttributes.Normal); SocketsocketData=CreateDataSocket(); SendCommand("STOR"+Path.GetFileName(strGuid)); if(!(iReplyCode==125||iReplyCode==150)) { thrownewIOException(strReply.Substring(4)); } FileStreaminput=newFileStream(strGuid,FileMode.Open,System.IO.FileAccess.Read,System.IO.FileShare.Read); intiBytes=0; while((iBytes=input.Read(buffer,0,buffer.Length))>0) { socketData.Send(buffer,iBytes,0); } input.Close(); File.Delete(strGuid); if(socketData.Connected) { socketData.Close(); } if(!(iReplyCode==226||iReplyCode==250)) { ReadReply(); if(!(iReplyCode==226||iReplyCode==250)) { thrownewIOException(strReply.Substring(4)); } } } #endregion #region目录操作 ///<summary> ///创建目录 ///</summary> ///<paramname="strDirName">目录名</param> publicvoidMkDir(stringstrDirName) { if(!bConnected) { Connect(); } SendCommand("MKD"+strDirName); if(iReplyCode!=257) { thrownewIOException(strReply.Substring(4)); } } ///<summary> ///删除目录 ///</summary> ///<paramname="strDirName">目录名</param> publicvoidRmDir(stringstrDirName) { if(!bConnected) { Connect(); } SendCommand("RMD"+strDirName); if(iReplyCode!=250) { thrownewIOException(strReply.Substring(4)); } } ///<summary> ///改变目录 ///</summary> ///<paramname="strDirName">新的工作目录名</param> publicvoidChDir(stringstrDirName) { if(strDirName.Equals(".")||strDirName.Equals("")) { return; } if(!bConnected) { Connect(); } SendCommand("CWD"+strDirName); if(iReplyCode!=250) { thrownewIOException(strReply.Substring(4)); } this.strRemotePath=strDirName; } #endregion #region内部函数 ///<summary> ///将一行应答字符串记录在strReply和strMsg,应答码记录在iReplyCode ///</summary> privatevoidReadReply() { strMsg=""; strReply=ReadLine(); iReplyCode=Int32.Parse(strReply.Substring(0,3)); } ///<summary> ///建立进行数据连接的socket ///</summary> ///<returns>数据连接socket</returns> privateSocketCreateDataSocket() { SendCommand("PASV"); if(iReplyCode!=227) { thrownewIOException(strReply.Substring(4)); } intindex1=strReply.IndexOf('('); intindex2=strReply.IndexOf(')'); stringipData=strReply.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("MalformedPASVstrReply:"+strReply); } if(ch==','||i+1==len) { try { parts[partCount++]=Int32.Parse(buf); buf=""; } catch(Exception) { thrownewIOException("MalformedPASVstrReply:"+strReply); } } } stringipAddress=parts[0]+"."+parts[1]+"."+parts[2]+"."+parts[3]; intport=(parts[4]<<8)+parts[5]; Sockets=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); IPEndPointep=newIPEndPoint(IPAddress.Parse(ipAddress),port); try { s.Connect(ep); } catch(Exception) { thrownewIOException("无法连接ftp服务器"); } returns; } ///<summary> ///关闭socket连接(用于登录以前) ///</summary> privatevoidCloseSocketConnect() { lock(obj) { if(socketControl!=null) { socketControl.Close(); socketControl=null; } bConnected=false; } } ///<summary> ///读取Socket返回的所有字符串 ///</summary> ///<returns>包含应答码的字符串行</returns> privatestringReadLine() { lock(obj) { while(true) { intiBytes=socketControl.Receive(buffer,buffer.Length,0); strMsg+=ASCII.GetString(buffer,0,iBytes); if(iBytes<buffer.Length) { break; } } } char[]seperator={'\n'}; string[]mess=strMsg.Split(seperator); if(strMsg.Length>2) { strMsg=mess[mess.Length-2]; } else { strMsg=mess[0]; } if(!strMsg.Substring(3,1).Equals(""))//返回字符串正确的是以应答码(如220开头,后面接一空格,再接问候字符串) { returnReadLine(); } returnstrMsg; } ///<summary> ///发送命令并获取应答码和最后一行应答字符串 ///</summary> ///<paramname="strCommand">命令</param> publicvoidSendCommand(StringstrCommand) { lock(obj) { Byte[]cmdBytes=Encoding.ASCII.GetBytes((strCommand+"\r\n").ToCharArray()); socketControl.Send(cmdBytes,cmdBytes.Length,0); Thread.Sleep(500); ReadReply(); } } #endregion } }
方法二:
usingSystem; usingSystem.Net; usingSystem.IO; usingSystem.Text; usingSystem.Net.Sockets; namespaceFtpLib { publicclassFTPFactory { 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() { remoteHost="localhost"; remotePath="."; remoteUser="anonymous"; remotePass=""; remotePort=21; 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=""; while(true) { intbytes=cSocket.Receive(buffer,buffer.Length,0); mes+=ASCII.GetString(buffer,0,bytes); if(bytes<buffer.Length) { break; } } 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(true); 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.Open); SocketcSocket=createDataSocket(); longoffset=0; if(resume) { offset=output.Length; if(offset>0) { 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=new FileStream(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!=257) { 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+"\r\n").ToCharArray()); Encoding.Default.GetBytes((command+"\r\n").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); IPEndPointep=new IPEndPoint(Dns.Resolve(ipAddress).AddressList[0],port); try { s.Connect(ep); } catch(Exception) { thrownewIOException("Can'tconnecttoremoteserver"); } returns; } } }
以上所述就是本文的全部内容了,希望大家能够喜欢。