通用类库-FTPClient帮助类,实现文件上传,目录操作,下载等动作

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通用类库-FTPClient帮助类,实现文件上传,目录操作,下载等动作相关的知识,希望对你有一定的参考价值。

直接上代码,这个也是我在网上找到的,自己测试修改后才公布出来的,大家可以放心使用,好的东西要分享,随时记录下来,好记性不如烂笔头,这个非常适合工作的。

  1 //-------------------------------------------------------------------------------------
  2 // All Rights Reserved , Copyright (C) 2016 , ZTO , Ltd .
  3 //-------------------------------------------------------------------------------------
  4 
  5 using System;
  6 using System.IO;
  7 using System.Net;
  8 using System.Net.Sockets;
  9 using System.Text;
 10 using System.Threading;
 11 
 12 namespace DotNet.Utilities
 13 {
 14     /// <summary>
 15     /// FTP 操作类客户端
 16     /// 
 17     /// 修改纪录
 18     /// 
 19     ///     2016-4-4  版本:1.0 杨恒连  创建,测试了连接和上传的功能
 20     /// 
 21     /// 版本:1.0
 22     ///
 23     /// <author>
 24     ///        <name>杨恒连</name>
 25     ///        <date>2016-4-4</date>
 26     /// </author>
 27     /// </summary>
 28     public class FTPClient
 29     {
 30         public static object obj = new object();
 31 
 32         #region 构造函数
 33         /// <summary>
 34         /// 缺省构造函数
 35         /// </summary>
 36         public FTPClient()
 37         {
 38             strRemoteHost = "";
 39             strRemotePath = "";
 40             strRemoteUser = "";
 41             strRemotePass = "";
 42             strRemotePort = 21;
 43             bConnected = false;
 44         }
 45 
 46         /// <summary>
 47         /// 构造函数
 48         /// </summary>
 49         public FTPClient(string remoteHost, string remotePath, string remoteUser, string remotePass, int remotePort)
 50         {
 51             strRemoteHost = remoteHost;
 52             strRemotePath = remotePath;
 53             strRemoteUser = remoteUser;
 54             strRemotePass = remotePass;
 55             strRemotePort = remotePort;
 56             Connect();
 57         }
 58         #endregion
 59 
 60         #region 字段
 61         private int strRemotePort;
 62         private Boolean bConnected;
 63         private string strRemoteHost;
 64         private string strRemotePass;
 65         private string strRemoteUser;
 66         private string strRemotePath;
 67 
 68         /// <summary>
 69         /// 服务器返回的应答信息(包含应答码)
 70         /// </summary>
 71         private string strMsg;
 72         /// <summary>
 73         /// 服务器返回的应答信息(包含应答码)
 74         /// </summary>
 75         private string strReply;
 76         /// <summary>
 77         /// 服务器返回的应答码
 78         /// </summary>
 79         private int iReplyCode;
 80         /// <summary>
 81         /// 进行控制连接的socket
 82         /// </summary>
 83         private Socket socketControl;
 84         /// <summary>
 85         /// 传输模式
 86         /// </summary>
 87         private TransferType trType;
 88         /// <summary>
 89         /// 接收和发送数据的缓冲区
 90         /// </summary>
 91         private static int BLOCK_SIZE = 512;
 92         /// <summary>
 93         /// 编码方式
 94         /// </summary>
 95         Encoding ASCII = Encoding.ASCII;
 96         /// <summary>
 97         /// 字节数组
 98         /// </summary>
 99         Byte[] buffer = new Byte[BLOCK_SIZE];
100         #endregion
101 
102         #region 属性
103         /// <summary>
104         /// FTP服务器IP地址
105         /// </summary>
106         public string RemoteHost
107         {
108             get
109             {
110                 return strRemoteHost;
111             }
112             set
113             {
114                 strRemoteHost = value;
115             }
116         }
117 
118         /// <summary>
119         /// FTP服务器端口
120         /// </summary>
121         public int RemotePort
122         {
123             get
124             {
125                 return strRemotePort;
126             }
127             set
128             {
129                 strRemotePort = value;
130             }
131         }
132 
133         /// <summary>
134         /// 当前服务器目录
135         /// </summary>
136         public string RemotePath
137         {
138             get
139             {
140                 return strRemotePath;
141             }
142             set
143             {
144                 strRemotePath = value;
145             }
146         }
147 
148         /// <summary>
149         /// 登录用户账号
150         /// </summary>
151         public string RemoteUser
152         {
153             set
154             {
155                 strRemoteUser = value;
156             }
157         }
158 
159         /// <summary>
160         /// 用户登录密码
161         /// </summary>
162         public string RemotePass
163         {
164             set
165             {
166                 strRemotePass = value;
167             }
168         }
169 
170         /// <summary>
171         /// 是否登录
172         /// </summary>
173         public bool Connected
174         {
175             get
176             {
177                 return bConnected;
178             }
179         }
180         #endregion
181 
182         #region 链接
183         /// <summary>
184         /// 建立连接 
185         /// </summary>
186         public void Connect()
187         {
188             lock (obj)
189             {
190                 socketControl = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
191                 IPEndPoint ep = new IPEndPoint(IPAddress.Parse(RemoteHost), strRemotePort);
192                 try
193                 {
194                     socketControl.Connect(ep);
195                 }
196                 catch (Exception)
197                 {
198                     throw new IOException("不能连接ftp服务器");
199                 }
200             }
201             ReadReply();
202             if (iReplyCode != 220)
203             {
204                 DisConnect();
205                 throw new IOException(strReply.Substring(4));
206             }
207             SendCommand("USER " + strRemoteUser);
208             if (!(iReplyCode == 331 || iReplyCode == 230))
209             {
210                 CloseSocketConnect();
211                 throw new IOException(strReply.Substring(4));
212             }
213             if (iReplyCode != 230)
214             {
215                 SendCommand("PASS " + strRemotePass);
216                 if (!(iReplyCode == 230 || iReplyCode == 202))
217                 {
218                     CloseSocketConnect();
219                     throw new IOException(strReply.Substring(4));
220                 }
221             }
222             bConnected = true;
223             ChDir(strRemotePath);
224         }
225 
226         /// <summary>
227         /// 关闭连接
228         /// </summary>
229         public void DisConnect()
230         {
231             if (socketControl != null)
232             {
233                 SendCommand("QUIT");
234             }
235             CloseSocketConnect();
236         }
237         #endregion
238 
239         #region 传输模式
240         /// <summary>
241         /// 传输模式:二进制类型、ASCII类型
242         /// </summary>
243         public enum TransferType { Binary, ASCII };
244 
245         /// <summary>
246         /// 设置传输模式
247         /// </summary>
248         /// <param name="ttType">传输模式</param>
249         public void SetTransferType(TransferType ttType)
250         {
251             if (ttType == TransferType.Binary)
252             {
253                 SendCommand("TYPE I");//binary类型传输
254             }
255             else
256             {
257                 SendCommand("TYPE A");//ASCII类型传输
258             }
259             if (iReplyCode != 200)
260             {
261                 throw new IOException(strReply.Substring(4));
262             }
263             else
264             {
265                 trType = ttType;
266             }
267         }
268 
269         /// <summary>
270         /// 获得传输模式
271         /// </summary>
272         /// <returns>传输模式</returns>
273         public TransferType GetTransferType()
274         {
275             return trType;
276         }
277         #endregion
278 
279         #region 文件操作
280         /// <summary>
281         /// 获得文件列表
282         /// </summary>
283         /// <param name="strMask">文件名的匹配字符串</param>
284         public string[] Dir(string strMask)
285         {
286             if (!bConnected)
287             {
288                 Connect();
289             }
290             Socket socketData = CreateDataSocket();
291             SendCommand("NLST " + strMask);
292             if (!(iReplyCode == 150 || iReplyCode == 125 || iReplyCode == 226))
293             {
294                 throw new IOException(strReply.Substring(4));
295             }
296             strMsg = "";
297             Thread.Sleep(2000);
298             while (true)
299             {
300                 int iBytes = socketData.Receive(buffer, buffer.Length, 0);
301                 strMsg += ASCII.GetString(buffer, 0, iBytes);
302                 if (iBytes < buffer.Length)
303                 {
304                     break;
305                 }
306             }
307             char[] seperator = { \n };
308             string[] strsFileList = strMsg.Split(seperator);
309             socketData.Close(); //数据socket关闭时也会有返回码
310             if (iReplyCode != 226)
311             {
312                 ReadReply();
313                 if (iReplyCode != 226)
314                 {
315 
316                     throw new IOException(strReply.Substring(4));
317                 }
318             }
319             return strsFileList;
320         }
321 
322         public void newPutByGuid(string strFileName, string strGuid)
323         {
324             if (!bConnected)
325             {
326                 Connect();
327             }
328             string str = strFileName.Substring(0, strFileName.LastIndexOf("\\"));
329             string strTypeName = strFileName.Substring(strFileName.LastIndexOf("."));
330             strGuid = str + "\\" + strGuid;
331             Socket socketData = CreateDataSocket();
332             SendCommand("STOR " + Path.GetFileName(strGuid));
333             if (!(iReplyCode == 125 || iReplyCode == 150))
334             {
335                 throw new IOException(strReply.Substring(4));
336             }
337             FileStream input = new FileStream(strGuid, FileMode.Open);
338             input.Flush();
339             int iBytes = 0;
340             while ((iBytes = input.Read(buffer, 0, buffer.Length)) > 0)
341             {
342                 socketData.Send(buffer, iBytes, 0);
343             }
344             input.Close();
345             if (socketData.Connected)
346             {
347                 socketData.Close();
348             }
349             if (!(iReplyCode == 226 || iReplyCode == 250))
350             {
351                 ReadReply();
352                 if (!(iReplyCode == 226 || iReplyCode == 250))
353                 {
354                     throw new IOException(strReply.Substring(4));
355                 }
356             }
357         }
358 
359         /// <summary>
360         /// 获取文件大小
361         /// </summary>
362         /// <param name="strFileName">文件名</param>
363         /// <returns>文件大小</returns>
364         public long GetFileSize(string strFileName)
365         {
366             if (!bConnected)
367             {
368                 Connect();
369             }
370             SendCommand("SIZE " + Path.GetFileName(strFileName));
371             long lSize = 0;
372             if (iReplyCode == 213)
373             {
374                 lSize = Int64.Parse(strReply.Substring(4));
375             }
376             else
377             {
378                 throw new IOException(strReply.Substring(4));
379             }
380             return lSize;
381         }
382 
383 
384         /// <summary>
385         /// 获取文件信息
386         /// </summary>
387         /// <param name="strFileName">文件名</param>
388         /// <returns>文件大小</returns>
389         public string GetFileInfo(string strFileName)
390         {
391             if (!bConnected)
392             {
393                 Connect();
394             }
395             Socket socketData = CreateDataSocket();
396             SendCommand("LIST " + strFileName);
397             string strResult = "";
398             if (!(iReplyCode == 150 || iReplyCode == 125
399                 || iReplyCode == 226 || iReplyCode == 250))
400             {
401                 throw new IOException(strReply.Substring(4));
402             }
403             byte[] b = new byte[512];
404             MemoryStream ms = new MemoryStream();
405 
406             while (true)
407             {
408                 int iBytes = socketData.Receive(b, b.Length, 0);
409                 ms.Write(b, 0, iBytes);
410                 if (iBytes <= 0)
411                 {
412 
413                     break;
414                 }
415             }
416             byte[] bt = ms.GetBuffer();
417             strResult = System.Text.Encoding.ASCII.GetString(bt);
418             ms.Close();
419             return strResult;
420         }
421 
422         /// <summary>
423         /// 删除
424         /// </summary>
425         /// <param name="strFileName">待删除文件名</param>
426         public void Delete(string strFileName)
427         {
428             if (!bConnected)
429             {
430                 Connect();
431             }
432             SendCommand("DELE " + strFileName);
433             if (iReplyCode != 250)
434             {
435                 throw new IOException(strReply.Substring(4));
436             }
437         }
438 
439         /// <summary>
440         /// 重命名(如果新文件名与已有文件重名,将覆盖已有文件)
441         /// </summary>
442         /// <param name="strOldFileName">旧文件名</param>
443         /// <param name="strNewFileName">新文件名</param>
444         public void Rename(string strOldFileName, string strNewFileName)
445         {
446             if (!bConnected)
447             {
448                 Connect();
449             }
450             SendCommand("RNFR " + strOldFileName);
451             if (iReplyCode != 350)
452             {
453                 throw new IOException(strReply.Substring(4));
454             }
455             //  如果新文件名与原有文件重名,将覆盖原有文件
456             SendCommand("RNTO " + strNewFileName);
457             if (iReplyCode != 250)
458             {
459                 throw new IOException(strReply.Substring(4));
460             }
461         }
462         #endregion
463 
464         #region 上传和下载
465         /// <summary>
466         /// 下载一批文件
467         /// </summary>
468         /// <param name="strFileNameMask">文件名的匹配字符串</param>
469         /// <param name="strFolder">本地目录(不得以\结束)</param>
470      

以上是关于通用类库-FTPClient帮助类,实现文件上传,目录操作,下载等动作的主要内容,如果未能解决你的问题,请参考以下文章

Java FTPClient实现文件上传下载

FTPClient - Java,上传文件

Java中使用FTPClient上传下载

FTP服务器文件上传的代码实现

在Servlet中利用Apache开源类库实现文件上传

FtpClient上传文件速度非常慢,而且大小为0,上传失败