C# FTP操作代码实现


C#  FTP 实现方式,废话不多说,直接上代码

  1 public class FtpClient
  2     {
  3         #region 构造函数
  4         /// 
  5         /// 创建FTP工具
  6         /// 
  7         /// 默认不使用SSL,使用二进制传输方式,使用被动模式
  8         /// 
  9         /// 
 10         /// 主机名称
 11         /// 用户名
 12         /// 密码
 13         public FtpClient(string host, string userId, string password)
 14             : this(host, userId, password, 21, null, false, true, true)
 15         {
 16         }
 17         /// 
 18         /// 创建FTP工具
 19         /// 
 20         /// 主机名称
 21         /// 用户名
 22         /// 密码
 23         /// 端口
 24         /// 允许Ssl
 25         /// 代理
 26         /// 允许二进制
 27         /// 允许被动模式
 28         public FtpClient(string host, string userId, string password, int port, IWebProxy proxy, bool enableSsl, bool useBinary, bool usePassive)
 29         {
 30             this.userId = userId;
 31             this.password = password;
 32             if (host.ToLower().StartsWith("ftp://"))
 33             {
 34                 this.host = host;
 35             }
 36             else
 37             {
 38                 this.host = "ftp://" + host;
 39             }
 40             this.port = port;
 41             this.proxy = proxy;
 42             this.enableSsl = enableSsl;
 43             this.useBinary = useBinary;
 44             this.usePassive = usePassive;
 45         }
 46         #endregion
 47         #region 主机
 48         private string host = string.Empty;
 49         /// 
 50         /// 主机
 51         /// 
 52         public string Host
 53         {
 54             get
 55             {
 56                 return this.host ?? string.Empty;
 57             }
 58         }
 59         #endregion
 60         #region 登录用户名
 61         private string userId = string.Empty;
 62         /// 
 63         /// 登录用户名
 64         /// 
 65         public string UserId
 66         {
 67             get
 68             {
 69                 return this.userId;
 70             }
 71         }
 72         #endregion
 73         #region 密码
 74         private string password = string.Empty;
 75         /// 
 76         /// 密码
 77         /// 
 78         public string Password
 79         {
 80             get
 81             {
 82                 return this.password;
 83             }
 84         }
 85         #endregion
 86         #region 代理
 87         IWebProxy proxy = null;
 88         /// 
 89         /// 代理
 90         /// 
 91         public IWebProxy Proxy
 92         {
 93             get
 94             {
 95                 return this.proxy;
 96             }
 97             set
 98             {
 99                 this.proxy = value;
100             }
101         }
102         #endregion
103         #region 端口
104         private int port = 21;
105         /// 
106         /// 端口
107         /// 
108         public int Port
109         {
110             get
111             {
112                 return port;
113             }
114             set
115             {
116                 this.port = value;
117             }
118         }
119         #endregion
120         #region 设置是否允许Ssl
121         private bool enableSsl = false;
122         /// 
123         /// EnableSsl
124         /// 
125         public bool EnableSsl
126         {
127             get
128             {
129                 return enableSsl;
130             }
131         }
132         #endregion
133         #region 使用被动模式
134         private bool usePassive = true;
135         /// 
136         /// 被动模式
137         /// 
138         public bool UsePassive
139         {
140             get
141             {
142                 return usePassive;
143             }
144             set
145             {
146                 this.usePassive = value;
147             }
148         }
149         #endregion
150         #region 二进制方式
151         private bool useBinary = true;
152         /// 
153         /// 二进制方式
154         /// 
155         public bool UseBinary
156         {
157             get
158             {
159                 return useBinary;
160             }
161             set
162             {
163                 this.useBinary = value;
164             }
165         }
166         #endregion
167         #region 远端路径
168         private string remotePath = "/";
169         /// 
170         /// 远端路径
171         /// 
172         ///     返回FTP服务器上的当前路径(可以是 / 或 /a/../ 的形式)
173         /// 
174         /// 
175         public string RemotePath
176         {
177             get
178             {
179                 return remotePath;
180             }
181             set
182             {
183                 string result = "/";
184                 if (!string.IsNullOrEmpty(value) && value != "/")
185                 {
186                     result = "/" + value.TrimStart('/').TrimEnd('/') + "/";
187                 }
188                 this.remotePath = result;
189             }
190         }
191         #endregion
192         #region 创建一个FTP连接
193         /// 
194         /// 创建一个FTP请求
195         /// 
196         /// 请求地址
197         /// 请求方法
198         /// FTP请求
199         private FtpWebRequest CreateRequest(string url, string method)
200         {
201             //建立连接
202             FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
203             request.Credentials = new NetworkCredential(this.userId, this.password);
204             request.Proxy = this.proxy;
205             request.KeepAlive = false;//命令执行完毕之后关闭连接
206             request.UseBinary = useBinary;
207             request.UsePassive = usePassive;
208             request.EnableSsl = enableSsl;
209             request.Method = method;
210             return request;
211         }
212         #endregion
213         #region 上传一个文件到远端路径下
214         /// 
215         /// 把文件上传到FTP服务器的RemotePath下
216         /// 
217         /// 本地文件信息
218         /// 要保存到FTP文件服务器上的名称
219         public bool Upload(FileInfo localFile, string remoteFileName)
220         {
221             bool result = false;
222             if (localFile.Exists)
223             {
224                 string url = Host.TrimEnd('/') + RemotePath + remoteFileName;
225                 FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.UploadFile);
226                 //上传数据
227                 using (Stream rs = request.GetRequestStream())
228                 using (FileStream fs = localFile.OpenRead())
229                 {
230                     byte[] buffer = new byte[4096];//4K
231                     int count = fs.Read(buffer, 0, buffer.Length);
232                     while (count > 0)
233                     {
234                         rs.Write(buffer, 0, count);
235                         count = fs.Read(buffer, 0, buffer.Length);
236                     }
237                     fs.Close();
238                     result = true;
239                 }
240                 return result;
241             }
242             throw new Exception(string.Format("本地文件不存在,文件路径:{0}", localFile.FullName));
243         }
244         #endregion
245         #region 从FTP服务器上下载文件
246         /// 
247         /// 从当前目录下下载文件
248         /// 
249         /// 如果本地文件存在,则从本地文件结束的位置开始下载.
250         /// 
251         /// 
252         /// 服务器上的文件名称
253         /// 本地文件名称
254         /// 返回一个值,指示是否下载成功
255         public bool Download(string serverName, string localName)
256         {
257             bool result = false;
258             using (FileStream fs = new FileStream(localName, FileMode.OpenOrCreate)) //创建或打开本地文件
259             {
260                 //建立连接
261                 string url = Host.TrimEnd('/') + RemotePath + serverName;
262                 FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.DownloadFile);
263                 request.ContentOffset = fs.Length;
264                 using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
265                 {
266                     fs.Position = fs.Length;
267                     byte[] buffer = new byte[4096];//4K
268                     int count = response.GetResponseStream().Read(buffer, 0, buffer.Length);
269                     while (count > 0)
270                     {
271                         fs.Write(buffer, 0, count);
272                         count = response.GetResponseStream().Read(buffer, 0, buffer.Length);
273                     }
274                     response.GetResponseStream().Close();
275                 }
276                 result = true;
277             }
278             return result;
279         }
280         #endregion
281         #region 重命名FTP服务器上的文件
282         /// 
283         /// 文件更名
284         /// 
285         /// 原文件名
286         /// 新文件名
287         /// 返回一个值,指示更名是否成功
288         public bool Rename(string oldFileName, string newFileName)
289         {
290             bool result = false;
291             //建立连接
292             string url = Host.TrimEnd('/') + RemotePath + oldFileName;
293             FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.Rename);
294             request.RenameTo = newFileName;
295             using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
296             {
297                 result = true;
298             }
299             return result;
300         }
301         #endregion
302         #region 从当前目录下获取文件列表
303         /// 
304         /// 获取当前目录下文件列表
305         /// 
306         /// 
307         public List<string> GetFileList()
308         {
309             List<string> result = new List<string>();
310             //建立连接
311             string url = Host.TrimEnd('/') + RemotePath;
312             FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.ListDirectory);
313             using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
314             {
315                 StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文文件名
316                 string line = reader.ReadLine();
317                 while (line != null)
318                 {
319                     result.Add(line);
320                     line = reader.ReadLine();
321                 }
322             }
323             return result;
324         }
325         #endregion
326         #region 从FTP服务器上获取文件和文件夹列表
327         /// 
328         /// 获取详细列表 从FTP服务器上获取文件和文件夹列表
329         /// 
330         /// 
331         public List<string> GetFileDetails()
332         {
333             List<string> result = new List<string>();
334             //建立连接
335             string url = Host.TrimEnd('/') + RemotePath;
336             FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.ListDirectoryDetails);
337             using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
338             {
339                 StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文文件名
340                 string line = reader.ReadLine();
341                 while (line != null)
342                 {
343                     result.Add(line);
344                     line = reader.ReadLine();
345                 }
346             }
347             return result;
348         }
349         #endregion
350         #region 从FTP服务器上删除文件
351         /// 
352         /// 删除FTP服务器上的文件
353         /// 
354         /// 文件名称
355         /// 返回一个值,指示是否删除成功
356         public bool DeleteFile(string fileName)
357         {
358             bool result = false;
359             //建立连接
360             string url = Host.TrimEnd('/') + RemotePath + fileName;
361             FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.DeleteFile);
362             using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
363             {
364                 result = true;
365             }
366             return result;
367         }
368         #endregion
369         #region 在FTP服务器上创建目录
370         /// 
371         /// 在当前目录下创建文件夹
372         /// 
373         /// 文件夹名称
374         /// 返回一个值,指示是否创建成功
375         public bool MakeDirectory(string dirName)
376         {
377             bool result = false;
378             //建立连接
379             string url = Host.TrimEnd('/') + RemotePath + dirName;
380             FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.MakeDirectory);
381             using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
382             {
383                 result = true;
384             }
385             return result;
386         }
387         #endregion
388         #region 从FTP服务器上删除目录
389         /// 
390         /// 删除文件夹
391         /// 
392         /// 文件夹名称
393         /// 返回一个值,指示是否删除成功
394         public bool DeleteDirectory(string dirName)
395         {
396             bool result = false;
397             //建立连接
398             string url = Host.TrimEnd('/') + RemotePath + dirName;
399             FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.RemoveDirectory);
400             using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
401             {
402                 result = true;
403             }
404             return result;
405         }
406         #endregion
407         #region 从FTP服务器上获取文件大小
408         /// 
409         /// 获取文件大小
410         /// 
411         /// 
412         /// 
413         public long GetFileSize(string fileName)
414         {
415             long result = 0;
416             //建立连接
417             string url = Host.TrimEnd('/') + RemotePath + fileName;
418             FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.GetFileSize);
419             using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
420             {
421                 result = response.ContentLength;
422             }
423             return result;
424         }
425         #endregion
426         #region 给FTP服务器上的文件追加内容
427         /// 
428         /// 给FTP服务器上的文件追加内容
429         /// 
430         /// 本地文件
431         /// FTP服务器上的文件
432         /// 返回一个值,指示是否追加成功
433         public bool Append(FileInfo localFile, string remoteFileName)
434         {
435             if (localFile.Exists)
436             {
437                 using (FileStream fs = new FileStream(localFile.FullName, FileMode.Open))
438                 {
439                     return Append(fs, remoteFileName);
440                 }
441             }
442             throw new Exception(string.Format("本地文件不存在,文件路径:{0}", localFile.FullName));
443         }
444         /// 
445         /// 给FTP服务器上的文件追加内容
446         /// 
447         /// 数据流(可通过设置偏移来实现从特定位置开始上传)
448         /// FTP服务器上的文件
449         /// 返回一个值,指示是否追加成功
450         public bool Append(Stream stream, string remoteFileName)
451         {
452             bool result = false;
453             if (stream != null && stream.CanRead)
454             {
455                 //建立连接
456                 string url = Host.TrimEnd('/') + RemotePath + remoteFileName;
457                 FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.AppendFile);
458                 using (Stream rs = request.GetRequestStream())
459                 {
460                     //上传数据
461                     byte[] buffer = new byte[4096];//4K
462                     int count = stream.Read(buffer, 0, buffer.Length);
463                     while (count > 0)
464                     {
465                         rs.Write(buffer, 0, count);
466                         count = stream.Read(buffer, 0, buffer.Length);
467                     }
468                     result = true;
469                 }
470             }
471             return result;
472         }
473         #endregion
474         #region 获取FTP服务器上的当前路径
475         /// 
476         /// 获取FTP服务器上的当前路径
477         /// 
478         public string CurrentDirectory
479         {
480             get
481             {
482                 string result = string.Empty;
483                 string url = Host.TrimEnd('/') + RemotePath;
484                 FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.PrintWorkingDirectory);
485                 using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
486                 {
487                     string temp = response.StatusDescription;
488                     int start = temp.IndexOf('"') + 1;
489                     int end = temp.LastIndexOf('"');
490                     if (end >= start)
491                     {
492                         result = temp.Substring(start, end - start);
493                     }
494                 }
495                 return result;
496             }
497         }
498         #endregion
499         #region 检查当前路径上是否存在某个文件
500         /// 
501         /// 检查文件是否存在
502         /// 
503         /// 要检查的文件名
504         /// 返回一个值,指示要检查的文件是否存在
505         public bool CheckFileExist(string fileName)
506         {
507             bool result = false;
508             if (fileName != null && fileName.Trim().Length > 0)
509             {
510                 fileName = fileName.Trim();
511                 List<string> files = GetFileList();
512                 if (files != null && files.Count > 0)
513                 {
514                     foreach (string file in files)
515                     {
516                         if (file.ToLower() == fileName.ToLower())
517                         {
518                             result = true;
519                             break;
520                         }
521                     }
522                 }
523             }
524             return result;
525         }
526         #endregion
527     }