赞
踩
1 public classFtpClient2 {3 public static object obj = new object();4
5 #region 构造函数
6 ///
7 ///缺省构造函数8 ///
9 publicFtpClient()10 {11 strRemoteHost = "10.132.26.86";12 strRemotePath = "00555";13 strRemoteUser = "uname";14 strRemotePass = "upass";15 strRemotePort = 21;16 bConnected = false;17 }18
19 ///
20 ///构造函数21 ///
22 public FtpClient(string remoteHost, string remotePath, string remoteUser, string remotePass, intremotePort)23 {24 strRemoteHost =remoteHost;25 strRemotePath =remotePath;26 strRemoteUser =remoteUser;27 strRemotePass =remotePass;28 strRemotePort =remotePort;29 Connect();30 }31
32 #endregion
33
34 #region 字段
35 private intstrRemotePort;36 privateBoolean bConnected;37 private stringstrRemoteHost;38 private stringstrRemotePass;39 private stringstrRemoteUser;40 private stringstrRemotePath;41
42 ///
43 ///服务器返回的应答信息(包含应答码)44 ///
45 private stringstrMsg;46 ///
47 ///服务器返回的应答信息(包含应答码)48 ///
49 private stringstrReply;50 ///
51 ///服务器返回的应答码52 ///
53 private intiReplyCode;54 ///
55 ///进行控制连接的socket56 ///
57 privateSocket socketControl;58 ///
59 ///传输模式60 ///
61 privateTransferType trType;62 ///
63 ///接收和发送数据的缓冲区64 ///
65 private static int BLOCK_SIZE = 512;66 ///
67 ///编码方式68 ///
69 Encoding ASCII =Encoding.ASCII;70 ///
71 ///字节数组72 ///
73 Byte[] buffer = newByte[BLOCK_SIZE];74 #endregion
75
76 #region 属性
77 ///
78 ///FTP服务器IP地址79 ///
80 public stringRemoteHost81 {82 get
83 {84 returnstrRemoteHost;85 }86 set
87 {88 strRemoteHost =value;89 }90 }91
92 ///
93 ///FTP服务器端口94 ///
95 public intRemotePort96 {97 get
98 {99 returnstrRemotePort;100 }101 set
102 {103 strRemotePort =value;104 }105 }106
107 ///
108 ///当前服务器目录109 ///
110 public stringRemotePath111 {112 get
113 {114 returnstrRemotePath;115 }116 set
117 {118 strRemotePath =value;119 }120 }121
122 ///
123 ///登录用户账号124 ///
125 public stringRemoteUser126 {127 set
128 {129 strRemoteUser =value;130 }131 }132
133 ///
134 ///用户登录密码135 ///
136 public stringRemotePass137 {138 set
139 {140 strRemotePass =value;141 }142 }143
144 ///
145 ///是否登录146 ///
147 public boolConnected148 {149 get
150 {151 returnbConnected;152 }153 }154 #endregion
155
156 #region 链接
157 ///
158 ///建立连接159 ///
160 public voidConnect()161 {162 lock(obj)163 {164 socketControl = newSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);165 IPEndPoint ep = newIPEndPoint(IPAddress.Parse(RemoteHost), strRemotePort);166 try
167 {168 socketControl.Connect(ep);169 }170 catch(Exception)171 {172 throw new IOException("不能连接ftp服务器");173 }174 }175 ReadReply();176 if (iReplyCode != 220)177 {178 DisConnect();179 throw new IOException(strReply.Substring(4));180 }181 SendCommand("USER" +strRemoteUser);182 if (!(iReplyCode == 331 || iReplyCode == 230))183 {184 CloseSocketConnect();185 throw new IOException(strReply.Substring(4));186 }187 if (iReplyCode != 230)188 {189 SendCommand("PASS" +strRemotePass);190 if (!(iReplyCode == 230 || iReplyCode == 202))191 {192 CloseSocketConnect();193 throw new IOException(strReply.Substring(4));194 }195 }196 bConnected = true;197 ChDir(strRemotePath);198 }199
200 ///
201 ///关闭连接202 ///
203 public voidDisConnect()204 {205 if (socketControl != null)206 {207 SendCommand("QUIT");208 }209 CloseSocketConnect();210 }211 #endregion
212
213 #region 传输模式
214 ///
215 ///传输模式:二进制类型、ASCII类型216 ///
217 public enumTransferType { Binary, ASCII };218
219 ///
220 ///设置传输模式221 ///
222 /// 传输模式
223 public voidSetTransferType(TransferType ttType)224 {225 if (ttType ==TransferType.Binary)226 {227 SendCommand("TYPE I");//binary类型传输
228 }229 else
230 {231 SendCommand("TYPE A");//ASCII类型传输
232 }233 if (iReplyCode != 200)234 {235 throw new IOException(strReply.Substring(4));236 }237 else
238 {239 trType =ttType;240 }241 }242
243 ///
244 ///获得传输模式245 ///
246 /// 传输模式
247 publicTransferType GetTransferType()248 {249 returntrType;250 }251 #endregion
252
253 #region 文件操作
254 ///
255 ///获得文件列表256 ///
257 /// 文件名的匹配字符串
258 public string[] Dir(stringstrMask)259 {260 if (!bConnected)261 {262 Connect();263 }264 Socket socketData =CreateDataSocket();265 SendCommand("NLST" +strMask);266 if (!(iReplyCode == 150 || iReplyCode == 125 || iReplyCode == 226))267 {268 throw new IOException(strReply.Substring(4));269 }270 strMsg = "";271 Thread.Sleep(2000);272 while (true)273 {274 int iBytes = socketData.Receive(buffer, buffer.Length, 0);275 strMsg += ASCII.GetString(buffer, 0, iBytes);276 if (iBytes
284 if (iReplyCode != 226)285 {286 ReadReply();287 if (iReplyCode != 226)288 {289
290 throw new IOException(strReply.Substring(4));291 }292 }293 returnstrsFileList;294 }295
296 public void newPutByGuid(string strFileName, stringstrGuid)297 {298 if (!bConnected)299 {300 Connect();301 }302 string str = strFileName.Substring(0, strFileName.LastIndexOf("\\"));303 string strTypeName = strFileName.Substring(strFileName.LastIndexOf("."));304 strGuid = str + "\\" +strGuid;305 Socket socketData =CreateDataSocket();306 SendCommand("STOR" +Path.GetFileName(strGuid));307 if (!(iReplyCode == 125 || iReplyCode == 150))308 {309 throw new IOException(strReply.Substring(4));310 }311 FileStream input = newFileStream(strGuid, FileMode.Open);312 input.Flush();313 int iBytes = 0;314 while ((iBytes = input.Read(buffer, 0, buffer.Length)) > 0)315 {316 socketData.Send(buffer, iBytes, 0);317 }318 input.Close();319 if(socketData.Connected)320 {321 socketData.Close();322 }323 if (!(iReplyCode == 226 || iReplyCode == 250))324 {325 ReadReply();326 if (!(iReplyCode == 226 || iReplyCode == 250))327 {328 throw new IOException(strReply.Substring(4));329 }330 }331 }332
333 ///
334 ///获取文件大小335 ///
336 /// 文件名
337 /// 文件大小
338 public long GetFileSize(stringstrFileName)339 {340 if (!bConnected)341 {342 Connect();343 }344 SendCommand("SIZE" +Path.GetFileName(strFileName));345 long lSize = 0;346 if (iReplyCode == 213)347 {348 lSize = Int64.Parse(strReply.Substring(4));349 }350 else
351 {352 throw new IOException(strReply.Substring(4));353 }354 returnlSize;355 }356
357
358 ///
359 ///获取文件信息360 ///
361 /// 文件名
362 /// 文件大小
363 public string GetFileInfo(stringstrFileName)364 {365 if (!bConnected)366 {367 Connect();368 }369 Socket socketData =CreateDataSocket();370 SendCommand("LIST" +strFileName);371 string strResult = "";372 if (!(iReplyCode == 150 || iReplyCode == 125
373 || iReplyCode == 226 || iReplyCode == 250))374 {375 throw new IOException(strReply.Substring(4));376 }377 byte[] b = new byte[512];378 MemoryStream ms = newMemoryStream();379
380 while (true)381 {382 int iBytes = socketData.Receive(b, b.Length, 0);383 ms.Write(b, 0, iBytes);384 if (iBytes <= 0)385 {386
387 break;388 }389 }390 byte[] bt =ms.GetBuffer();391 strResult =System.Text.Encoding.ASCII.GetString(bt);392 ms.Close();393 returnstrResult;394 }395
396 ///
397 ///删除398 ///
399 /// 待删除文件名
400 public void Delete(stringstrFileName)401 {402 if (!bConnected)403 {404 Connect();405 }406 SendCommand("DELE" +strFileName);407 if (iReplyCode != 250)408 {409 throw new IOException(strReply.Substring(4));410 }411 }412
413 ///
414 ///重命名(如果新文件名与已有文件重名,将覆盖已有文件)415 ///
416 /// 旧文件名
417 /// 新文件名
418 public void Rename(string strOldFileName, stringstrNewFileName)419 {420 if (!bConnected)421 {422 Connect();423 }424 SendCommand("RNFR" +strOldFileName);425 if (iReplyCode != 350)426 {427 throw new IOException(strReply.Substring(4));428 }429 //如果新文件名与原有文件重名,将覆盖原有文件
430 SendCommand("RNTO" +strNewFileName);431 if (iReplyCode != 250)432 {433 throw new IOException(strReply.Substring(4));434 }435 }436 #endregion
437
438 #region 上传和下载
439 ///
440 ///下载一批文件441 ///
442 /// 文件名的匹配字符串
443 /// 本地目录(不得以\结束)
444 public void Get(string strFileNameMask, stringstrFolder)445 {446 if (!bConnected)447 {448 Connect();449 }450 string[] strFiles =Dir(strFileNameMask);451 foreach (string strFile instrFiles)452 {453 if (!strFile.Equals(""))//一般来说strFiles的最后一个元素可能是空字符串
454 {455 Get(strFile, strFolder, strFile);456 }457 }458 }459
460 ///
461 ///下载一个文件462 ///
463 /// 要下载的文件名
464 /// 本地目录(不得以\结束)
465 /// 保存在本地时的文件名
466 public void Get(string strRemoteFileName, string strFolder, stringstrLocalFileName)467 {468 Socket socketData =CreateDataSocket();469 try
470 {471 if (!bConnected)472 {473 Connect();474 }475 SetTransferType(TransferType.Binary);476 if (strLocalFileName.Equals(""))477 {478 strLocalFileName =strRemoteFileName;479 }480 SendCommand("RETR" +strRemoteFileName);481 if (!(iReplyCode == 150 || iReplyCode == 125 || iReplyCode == 226 || iReplyCode == 250))482 {483 throw new IOException(strReply.Substring(4));484 }485 FileStream output = new FileStream(strFolder + "\\" +strLocalFileName, FileMode.Create);486 while (true)487 {488 int iBytes = socketData.Receive(buffer, buffer.Length, 0);489 output.Write(buffer, 0, iBytes);490 if (iBytes <= 0)491 {492 break;493 }494 }495 output.Close();496 if(socketData.Connected)497 {498 socketData.Close();499 }500 if (!(iReplyCode == 226 || iReplyCode == 250))501 {502 ReadReply();503 if (!(iReplyCode == 226 || iReplyCode == 250))504 {505 throw new IOException(strReply.Substring(4));506 }507 }508 }509 catch
510 {511 socketData.Close();512 socketData = null;513 socketControl.Close();514 bConnected = false;515 socketControl = null;516 }517 }518
519 ///
520 ///下载一个文件521 ///
522 /// 要下载的文件名
523 /// 本地目录(不得以\结束)
524 /// 保存在本地时的文件名
525 public void GetNoBinary(string strRemoteFileName, string strFolder, stringstrLocalFileName)526 {527 if (!bConnected)528 {529 Connect();530 }531
532 if (strLocalFileName.Equals(""))533 {534 strLocalFileName =strRemoteFileName;535 }536 Socket socketData =CreateDataSocket();537 SendCommand("RETR" +strRemoteFileName);538 if (!(iReplyCode == 150 || iReplyCode == 125 || iReplyCode == 226 || iReplyCode == 250))539 {540 throw new IOException(strReply.Substring(4));541 }542 FileStream output = new FileStream(strFolder + "\\" +strLocalFileName, FileMode.Create);543 while (true)544 {545 int iBytes = socketData.Receive(buffer, buffer.Length, 0);546 output.Write(buffer, 0, iBytes);547 if (iBytes <= 0)548 {549 break;550 }551 }552 output.Close();553 if(socketData.Connected)554 {555 socketData.Close();556 }557 if (!(iReplyCode == 226 || iReplyCode == 250))558 {559 ReadReply();560 if (!(iReplyCode == 226 || iReplyCode == 250))561 {562 throw new IOException(strReply.Substring(4));563 }564 }565 }566
567 ///
568 ///上传一批文件569 ///
570 /// 本地目录(不得以\结束)
571 /// 文件名匹配字符(可以包含*和?)
572 public void Put(string strFolder, stringstrFileNameMask)573 {574 string[] strFiles =Directory.GetFiles(strFolder, strFileNameMask);575 foreach (string strFile instrFiles)576 {577 Put(strFile);578 }579 }580
581 ///
582 ///上传一个文件583 ///
584 /// 本地文件名
585 public void Put(stringstrFileName)586 {587 if (!bConnected)588 {589 Connect();590 }591 Socket socketData =CreateDataSocket();592 if (Path.GetExtension(strFileName) == "")593 SendCommand("STOR" +Path.GetFileNameWithoutExtension(strFileName));594 else
595 SendCommand("STOR" +Path.GetFileName(strFileName));596
597 if (!(iReplyCode == 125 || iReplyCode == 150))598 {599 throw new IOException(strReply.Substring(4));600 }601
602 FileStream input = newFileStream(strFileName, FileMode.Open);603 int iBytes = 0;604 while ((iBytes = input.Read(buffer, 0, buffer.Length)) > 0)605 {606 socketData.Send(buffer, iBytes, 0);607 }608 input.Close();609 if(socketData.Connected)610 {611 socketData.Close();612 }613 if (!(iReplyCode == 226 || iReplyCode == 250 || iReplyCode == 200))614 {615 ReadReply();616 if (!(iReplyCode == 226 || iReplyCode == 250 || iReplyCode == 200))617 {618 throw new IOException(strReply.Substring(4));619 }620 }621 }622
623
624 ///
625 ///上传一个文件626 ///
627 /// 本地文件名
628 public void PutByGuid(string strFileName, stringstrGuid)629 {630 if (!bConnected)631 {632 Connect();633 }634 string str = strFileName.Substring(0, strFileName.LastIndexOf("\\"));635 string strTypeName = strFileName.Substring(strFileName.LastIndexOf("."));636 strGuid = str + "\\" +strGuid;637 System.IO.File.Copy(strFileName, strGuid);638 System.IO.File.SetAttributes(strGuid, System.IO.FileAttributes.Normal);639 Socket socketData =CreateDataSocket();640 SendCommand("STOR" +Path.GetFileName(strGuid));641 if (!(iReplyCode == 125 || iReplyCode == 150))642 {643 throw new IOException(strReply.Substring(4));644 }645 FileStream input = newFileStream(strGuid, FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);646 int iBytes = 0;647 while ((iBytes = input.Read(buffer, 0, buffer.Length)) > 0)648 {649 socketData.Send(buffer, iBytes, 0);650 }651 input.Close();652 File.Delete(strGuid);653 if(socketData.Connected)654 {655 socketData.Close();656 }657 if (!(iReplyCode == 226 || iReplyCode == 250))658 {659 ReadReply();660 if (!(iReplyCode == 226 || iReplyCode == 250))661 {662 throw new IOException(strReply.Substring(4));663 }664 }665 }666 #endregion
667
668 #region 目录操作
669 ///
670 ///创建目录671 ///
672 /// 目录名
673 public void MkDir(stringstrDirName)674 {675 if (!bConnected)676 {677 Connect();678 }679 SendCommand("MKD" +strDirName);680 if (iReplyCode != 257)681 {682 throw new IOException(strReply.Substring(4));683 }684 }685
686 ///
687 ///删除目录688 ///
689 /// 目录名
690 public void RmDir(stringstrDirName)691 {692 if (!bConnected)693 {694 Connect();695 }696 SendCommand("RMD" +strDirName);697 if (iReplyCode != 250)698 {699 throw new IOException(strReply.Substring(4));700 }701 }702
703 ///
704 ///改变目录705 ///
706 /// 新的工作目录名
707 public void ChDir(stringstrDirName)708 {709 if (strDirName.Equals(".") || strDirName.Equals(""))710 {711 return;712 }713 if (!bConnected)714 {715 Connect();716 }717 SendCommand("CWD" +strDirName);718 if (iReplyCode != 250)719 {720 throw new IOException(strReply.Substring(4));721 }722 this.strRemotePath =strDirName;723 }724 #endregion
725
726 #region 内部函数
727 ///
728 ///将一行应答字符串记录在strReply和strMsg,应答码记录在iReplyCode729 ///
730 private voidReadReply()731 {732 strMsg = "";733 strReply =ReadLine();734 iReplyCode = Int32.Parse(strReply.Substring(0, 3));735 }736
737 ///
738 ///建立进行数据连接的socket739 ///
740 /// 数据连接socket
741 privateSocket CreateDataSocket()742 {743 SendCommand("PASV");744 if (iReplyCode != 227)745 {746 throw new IOException(strReply.Substring(4));747 }748 int index1 = strReply.IndexOf('(');749 int index2 = strReply.IndexOf(')');750 string ipData = strReply.Substring(index1 + 1, index2 - index1 - 1);751 int[] parts = new int[6];752 int len =ipData.Length;753 int partCount = 0;754 string buf = "";755 for (int i = 0; i < len && partCount <= 6; i++)756 {757 char ch = Char.Parse(ipData.Substring(i, 1));758 if(Char.IsDigit(ch))759 buf +=ch;760 else if (ch != ',')761 {762 throw new IOException("Malformed PASV strReply:" +strReply);763 }764 if (ch == ',' || i + 1 ==len)765 {766 try
767 {768 parts[partCount++] =Int32.Parse(buf);769 buf = "";770 }771 catch(Exception)772 {773 throw new IOException("Malformed PASV strReply:" +strReply);774 }775 }776 }777 string ipAddress = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3];778 int port = (parts[4] << 8) + parts[5];779 Socket s = newSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);780 IPEndPoint ep = newIPEndPoint(IPAddress.Parse(ipAddress), port);781 try
782 {783 s.Connect(ep);784 }785 catch(Exception)786 {787 throw new IOException("无法连接ftp服务器");788 }789 returns;790 }791
792 ///
793 ///关闭socket连接(用于登录以前)794 ///
795 private voidCloseSocketConnect()796 {797 lock(obj)798 {799 if (socketControl != null)800 {801 socketControl.Close();802 socketControl = null;803 }804 bConnected = false;805 }806 }807
808 ///
809 ///读取Socket返回的所有字符串810 ///
811 /// 包含应答码的字符串行
812 private stringReadLine()813 {814 lock(obj)815 {816 while (true)817 {818 int iBytes = socketControl.Receive(buffer, buffer.Length, 0);819 strMsg += ASCII.GetString(buffer, 0, iBytes);820 if (iBytes 2)829 {830 strMsg = mess[mess.Length - 2];831 }832 else
833 {834 strMsg = mess[0];835 }836 if (!strMsg.Substring(3, 1).Equals(" ")) //返回字符串正确的是以应答码(如220开头,后面接一空格,再接问候字符串)
837 {838 returnReadLine();839 }840 returnstrMsg;841 }842
843 ///
844 ///发送命令并获取应答码和最后一行应答字符串845 ///
846 /// 命令
847 public voidSendCommand(String strCommand)848 {849 lock(obj)850 {851 Byte[] cmdBytes = Encoding.ASCII.GetBytes((strCommand + "\r\n").ToCharArray());852 socketControl.Send(cmdBytes, cmdBytes.Length, 0);853 Thread.Sleep(500);854 ReadReply();855 }856 }857 #endregion
858 }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。