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登陸所需的用戶名和密碼。
1 private string ftpUser = "username"; //ftp用戶名 2 private string ftpPassword = "12345"; //ftp密碼
接着就是上傳、下載、重命名、刪除和檢查存在的方法了。
1.上傳文件到ftp
上傳的方法代碼如下:
1 /// <summary> 2 /// 上傳文件 3 /// </summary> 4 /// <param name="localFile1">本地文件路徑及文件名</param> 5 /// <param name="ftpFileName">ftp文件路徑及文件名(文件名可重命名)</param> 6 /// <returns>返回bool值</returns> 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[buffLength]; 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 /// <summary> 5 /// 構造函數,提供初始化數據的功能,打開Ftp站點 6 /// </summary> 7 public class1() 8 { 9 certificate = new NetworkCredential("administrator", "cnugis202"); 10 } 11 /// <summary> 12 /// 創建FTP請求 13 /// </summary> 14 /// <param name="uri">ftp://myserver/upload.txt</param> 15 /// <param name="method">Upload/Download</param> 16 /// <returns></returns> 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[length + offSet]; 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 /// <summary> 2 /// 下載文件 3 /// </summary> 4 /// <param name="localFileName">下載的ftp的文件路徑及文件名</param> 5 /// <param name="ftpFileName">本地文件路徑及文件名(文件名可重命名)</param> 6 /// <returns>返回值</returns> 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[bufferSize]; 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 /// <summary> 2 /// 重命名 3 /// </summary> 4 /// <param name="ftpPath">ftp文件路徑(不包含文件名)</param> 5 /// <param name="currentFilename">ftp文件的當前文件名</param> 6 /// <param name="newFilename">ftp文件的重命名后的新文件名</param> 7 /// <returns>返回值</returns> 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 /// <summary> 2 /// 刪除文件 3 /// </summary> 4 /// <param name="ftpPath">ftp文件路徑(不包含文件名)</param> 5 /// <param name="ftpName">文件名</param> 6 /// <returns>返回值</returns> 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 /// <summary> 2 /// 檢查文件是否存在 3 /// </summary> 4 /// <param name="ftpPath"></param> 5 /// <param name="ftpName"></param> 6 /// <returns></returns> 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("<script>alert('文件存在!')</script>"); 6 } 7 else 8 { 9 this.Response.Write("<script>alert('文件不存在!')</script>"); 10 }