在水一万 发表于 2015-5-26 12:41:38

ASP.NET FTP的操作(包括上传、下载、重命名、删除、检查是否存在)

  ASP.NET中,有时候会遇到把文件上传到ftp或者从ftp上下载文件的操作,下文针对这些操作一一展开。
  首先,引用命名空间。



1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5
6 using System.Text;
7 using System.Net;
8 using System.Data;
9 using System.IO;
10 using System.ComponentModel;
  其中,前四个是新建ASP.NET时自动添加的,后五个为手动添加。
  然后,在class1类中(假设新添加的类为class1)声明全局变量,即ftp登陆所需的用户名和密码。



1private string ftpUser = "username";   //ftp用户名
2private string ftpPassword = "12345";   //ftp密码
  接着就是上传、下载、重命名、删除和检查存在的方法了。
  1.上传文件到ftp
  上传的方法代码如下:



1         ///
2         /// 上传文件
3         ///
4         /// 本地文件路径及文件名
5         /// ftp文件路径及文件名(文件名可重命名)
6         /// 返回bool值
7         public bool fileUpload(string localFile1, string ftpFileName)
8         {
9             FileInfo localFile = new FileInfo(localFile1);
10             bool success = false;
11             FtpWebRequest ftpWebRequest = null;
12             FileStream localFileStream = null;
13             Stream requestStream = null;
14             try
15             {
16               string uri = ftpFileName;
17               ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
18               ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
19               ftpWebRequest.UseBinary = true;//指定数据传输类型为二进制
20               ftpWebRequest.KeepAlive = false;//成功执行一个命令后连接被关闭
21               ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;// 指定执行什么命令
22               ftpWebRequest.ContentLength = localFile.Length;//上传文件时通知服务器文件的大小
23               int buffLength = 20480;// 缓冲大小设置为20kb
24               byte[] buff = new byte;
25               int contentLen;
26               localFileStream = localFile.OpenRead();//打开一个文件流去读上传的文件
27               requestStream = ftpWebRequest.GetRequestStream();//把上传的文件写入流
28               contentLen = localFileStream.Read(buff, 0, buffLength);//每次读文件流的2kb
29               while (contentLen != 0)// 流内容没有结束
30               {
31                     // 把内容从file stream 写入 upload stream
32                     requestStream.Write(buff, 0, contentLen);
33                     contentLen = localFileStream.Read(buff, 0, buffLength);
34               }
35               success = true;
36             }
37             catch (Exception)
38             {
39               success = false;
40             }
41             finally
42             {
43               if (requestStream != null)
44               {
45                     requestStream.Close();
46               }
47               if (localFileStream != null)
48               {
49                     localFileStream.Close();
50               }
51             }
52             return success;
53         }
  调用方法为实例化类对象,然后通过类对象直接调用。
  示例:假设该方法包含在class1类中(以下方法均假设包含在class1中),则有:



1   class1 ftpClient1 = new class1();//实例化类FTPClient
2   ftpClient1.fileUpload("D:\\456.png", "ftp://192.18.13.11/123.png");    //上传文件
  另一种方法支持断点续传的方法如下:
  添加命名空间:



1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5
6 using System.IO;
7 using System.Net;
8 using System.Net.Security;
9 using System.Collections;
10
11 using System.Security.Cryptography.X509Certificates;
12
13 using System.Web.Configuration;
  class1类中的代码如下:



1   public class class1
2   {
3         private NetworkCredential certificate;
4         ///
5         /// 构造函数,提供初始化数据的功能,打开Ftp站点
6         ///
7         public class1()
8         {
9             certificate = new NetworkCredential("administrator", "cnugis202");
10         }
11         ///
12         /// 创建FTP请求
13         ///
14         /// ftp://myserver/upload.txt
15         /// Upload/Download
16         ///
17         private FtpWebRequest CreateFtpWebRequest(Uri uri, string method)
18         {
19             FtpWebRequest ftpClientRequest = (FtpWebRequest)WebRequest.Create(uri);
20             ftpClientRequest.Proxy = null;
21             ftpClientRequest.Credentials = certificate;
22             ftpClientRequest.KeepAlive = true;
23             ftpClientRequest.UseBinary = true;
24             ftpClientRequest.UsePassive = true;
25             ftpClientRequest.Method = method;
26             //ftpClientRequest.Timeout = -1;
27             return ftpClientRequest;
28         }
29         //支持断点续传
30         public bool UploadFile(string sourceFile, Uri destinationPath, int offSet, string ftpMethod)
31         {
32             try
33             {
34               FileInfo file = new FileInfo(sourceFile);
35               Uri uri = new Uri(destinationPath.AbsoluteUri + "/" + file.Name);
36               FtpWebRequest request = CreateFtpWebRequest(uri, ftpMethod);
37               request.ContentOffset = offSet;
38               Stream requestStream = request.GetRequestStream();//需要获取文件的流
39               FileStream fileStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read);//创建存储文件的流
40               int sourceLength = (int)fileStream.Length;
41               offSet = CopyDataToDestination(fileStream, requestStream, offSet);
42               WebResponse response = request.GetResponse();
43               response.Close();
44               if (offSet != 0)
45               {
46                     UploadFile(sourceFile, destinationPath, offSet, WebRequestMethods.Ftp.AppendFile);
47               }
48             }
49             catch (Exception ex)
50             {
51               ex.ToString();
52               return false;
53             }
54             return true;
55         }
56         private int CopyDataToDestination(Stream sourceStream, Stream destinationStream, int offSet)
57         {
58             try
59             {
60               int sourceLength = (int)sourceStream.Length;
61               int length = sourceLength - offSet;
62               byte[] buffer = new byte;
63               int bytesRead = sourceStream.Read(buffer, offSet, length);
64               while (bytesRead != 0)
65               {
66                     destinationStream.Write(buffer, 0, bytesRead);
67                     bytesRead = sourceStream.Read(buffer, 0, length);
68                     length = length - bytesRead;
69                     offSet = (bytesRead == 0) ? 0 : (sourceLength - length);//(length - bytesRead);                  
70               }
71             }
72             catch (Exception ex)
73             {
74               string error = ex.ToString();
75               return offSet;
76             }
77             finally
78             {
79               destinationStream.Close();
80               sourceStream.Close();
81             }
82             return offSet;
83         }
84   }
  调用方法为:



1 class1 ftpClientService = new class1();   //实例化class1类对象
2 ftpClientService.UploadFile("D:\\456.png",new Uri("ftp://192.18.13.11/123.png“), 0, WebRequestMethods.Ftp.UploadFile);//调用class1类的UploadFile方法上传
  2.从ftp下载文件
  下载的方法代码如下:



1         ///
2         /// 下载文件
3         ///
4         /// 下载的ftp的文件路径及文件名
5         /// 本地文件路径及文件名(文件名可重命名)
6         /// 返回值
7         public bool fileDownload(string ftpFileName, string localFileName)
8         {
9             bool success = false;
10             FtpWebRequest ftpWebRequest = null;
11             FtpWebResponse ftpWebResponse = null;
12             Stream ftpResponseStream = null;
13             FileStream outputStream = null;
14             try
15             {
16               outputStream = new FileStream(localFileName, FileMode.Create);
17               string uri = ftpFileName;
18               ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
19               ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
20               ftpWebRequest.UseBinary = true;
21               ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;
22               ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
23               ftpResponseStream = ftpWebResponse.GetResponseStream();
24               long contentLength = ftpWebResponse.ContentLength;
25               int bufferSize = 20480;
26               byte[] buffer = new byte;
27               int readCount;
28               readCount = ftpResponseStream.Read(buffer, 0, bufferSize);
29               while (readCount > 0)
30               {
31                     outputStream.Write(buffer, 0, readCount);
32                     readCount = ftpResponseStream.Read(buffer, 0, bufferSize);
33               }
34               success = true;
35             }
36             catch (Exception)
37             {
38               success = false;
39             }
40             finally
41             {
42               if (outputStream != null)
43               {
44                     outputStream.Close();
45               }
46               if (ftpResponseStream != null)
47               {
48                     ftpResponseStream.Close();
49               }
50               if (ftpWebResponse != null)
51               {
52                     ftpWebResponse.Close();
53               }
54             }
55             return success;
56         }
  调用方法为:



1        class1 ftpClient2 = new class1();//实例化类FTPClient
2             ftpClient2.fileDownload(ftp://192.18.13.11/123.png","D:\\123.png);   //下载文件
  3.在ftp上重命名文件
  对ftp文件的重命名,方法代码如下:



1         ///
2         /// 重命名
3         ///
4         /// ftp文件路径(不包含文件名)
5         /// ftp文件的当前文件名
6         /// ftp文件的重命名后的新文件名
7         /// 返回值
8         public bool fileRename(string ftpPath, string currentFileName, string newFileName)
9         {
10             bool success = false;
11             FtpWebRequest ftpWebRequest = null;
12             FtpWebResponse ftpWebResponse = null;
13             Stream ftpResponseStream = null;
14             try
15             {
16               string uri = ftpPath + currentFileName;
17               ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
18               ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
19               ftpWebRequest.UseBinary = true;
20               ftpWebRequest.Method = WebRequestMethods.Ftp.Rename;
21               ftpWebRequest.RenameTo = newFileName;
22               ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
23               ftpResponseStream = ftpWebResponse.GetResponseStream();
24             }
25             catch (Exception)
26             {
27               success = false;
28             }
29             finally
30             {
31               if (ftpResponseStream != null)
32               {
33                     ftpResponseStream.Close();
34               }
35               if (ftpWebResponse != null)
36               {
37                     ftpWebResponse.Close();
38               }
39             }
40             return success;
41         }
  调用方法为:



1             class1 ftpClient3 = new class1();//实例化类对象
2             ftpClient3.fileRename(ftp://192.18.13.11/, "123.png", "456.png");      //ftp上重命名文件
  
  4.删除ftp上的文件
  
删除ftp上文件的方法代码为:



1         ///
2         /// 删除文件
3         ///
4         /// ftp文件路径(不包含文件名)
5         /// 文件名
6         /// 返回值
7         public bool fileDelete(string ftpPath, string ftpName)
8         {
9             bool success = false;
10             FtpWebRequest ftpWebRequest = null;
11             FtpWebResponse ftpWebResponse = null;
12             Stream ftpResponseStream = null;
13             StreamReader streamReader = null;
14             try
15             {
16               string uri = ftpPath + ftpName;
17               ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
18               ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
19               ftpWebRequest.KeepAlive = false;
20               ftpWebRequest.Method = WebRequestMethods.Ftp.DeleteFile;
21               ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
22               long size = ftpWebResponse.ContentLength;
23               ftpResponseStream = ftpWebResponse.GetResponseStream();
24               streamReader = new StreamReader(ftpResponseStream);
25               string result = String.Empty;
26               result = streamReader.ReadToEnd();
27               success = true;
28             }
29             catch (Exception)
30             {
31               success = false;
32             }
33             finally
34             {
35               if (streamReader != null)
36               {
37                     streamReader.Close();
38               }
39               if (ftpResponseStream != null)
40               {
41                     ftpResponseStream.Close();
42               }
43               if (ftpWebResponse != null)
44               {
45                     ftpWebResponse.Close();
46               }
47             }
48             return success;
49         }
  调用方法:



1             class1 ftpClient4 = new class1();//实例化类对象
2             ftpClient4.fileDelete(ftp://192.18.13.11/, "456.png");   //删除ftp文件
  5.检查ftp上某文件是否存在
  方法代码为:



1         ///
2         /// 检查文件是否存在
3         ///
4         ///
5         ///
6         ///
7         public bool fileCheckExist(string ftpPath, string ftpName)
8         {
9             bool success = false;
10             FtpWebRequest ftpWebRequest = null;
11             WebResponse webResponse = null;
12             StreamReader reader = null;
13             try
14             {
15               string url = ftpPath;
16               ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
17               ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
18               ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectory;
19               ftpWebRequest.KeepAlive = false;
20               webResponse = ftpWebRequest.GetResponse();
21               reader = new StreamReader(webResponse.GetResponseStream());
22               string line = reader.ReadLine();
23               while (line != null)
24               {
25                     if (line == ftpName)
26                     {
27                         success = true;
28                         break;
29                     }
30                     line = reader.ReadLine();
31               }
32             }
33             catch (Exception)
34             {
35               success = false;
36             }
37             finally
38             {
39               if (reader != null)
40               {
41                     reader.Close();
42               }
43               if (webResponse != null)
44               {
45                     webResponse.Close();
46               }
47             }
48             return success;
49         }
  调用方法为:



1             class1 ftpClient5 = new class1();//实例化类对象
2             bool flag = ftpClient5.fileCheckExist(ftp://192.18.13.11/, "123.png");    //检查文件是否存在
3             if (flag == true)
4             {
5               this.Response.Write("alert('文件存在!')");
6             }
7             else
8             {
9               this.Response.Write("alert('文件不存在!')");
10             }
  
页: [1]
查看完整版本: ASP.NET FTP的操作(包括上传、下载、重命名、删除、检查是否存在)