1 /// <summary> 2 /// 上傳文件 3 /// </summary> 4 /// <param name="fileinfo">需要上傳的文件</param> 5 /// <param name="targetDir">目標路徑</param> 6 /// <param name="hostname">ftp地址</param> 7 /// <param name="username">ftp用戶名</param> 8 /// <param name="password">ftp密碼</param> 9 public static void UploadFile(FileInfo fileinfo, string targetDir, string hostname, string username, string password) 10 { 11 //1. check target 12 string target; 13 if (targetDir.Trim() == "") 14 { 15 return; 16 } 17 target = Guid.NewGuid().ToString(); //使用臨時文件名 18 19 20 string URI = "FTP://" + hostname + "/" + targetDir + "/" + target; 21 ///WebClient webcl = new WebClient(); 22 System.Net.FtpWebRequest ftp = GetRequest(URI, username, password); 23 24 //設置FTP命令 設置所要執行的FTP命令, 25 //ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假設此處為顯示指定路徑下的文件列表 26 ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile; 27 //指定文件傳輸的數據類型 28 ftp.UseBinary = true; 29 ftp.UsePassive = true; 30 31 //告訴ftp文件大小 32 ftp.ContentLength = fileinfo.Length; 33 //緩沖大小設置為2KB 34 const int BufferSize = 2048; 35 byte[] content = new byte[BufferSize - 1 + 1]; 36 int dataRead; 37 38 //打開一個文件流 (System.IO.FileStream) 去讀上傳的文件 39 using (FileStream fs = fileinfo.OpenRead()) 40 { 41 try 42 { 43 //把上傳的文件寫入流 44 using (Stream rs = ftp.GetRequestStream()) 45 { 46 do 47 { 48 //每次讀文件流的2KB 49 dataRead = fs.Read(content, 0, BufferSize); 50 rs.Write(content, 0, dataRead); 51 } while (!(dataRead < BufferSize)); 52 rs.Close(); 53 } 54 55 } 56 catch (Exception ex) { } 57 finally 58 { 59 fs.Close(); 60 } 61 62 } 63 64 ftp = null; 65 //設置FTP命令 66 ftp = GetRequest(URI, username, password); 67 ftp.Method = System.Net.WebRequestMethods.Ftp.Rename; //改名 68 ftp.RenameTo = fileinfo.Name; 69 try 70 { 71 ftp.GetResponse(); 72 } 73 catch (Exception ex) 74 { 75 ftp = GetRequest(URI, username, password); 76 ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //刪除 77 ftp.GetResponse(); 78 throw ex; 79 } 80 finally 81 { 82 //fileinfo.Delete(); 83 } 84 85 // 可以記錄一個日志 "上傳" + fileinfo.FullName + "上傳到" + "FTP://" + hostname + "/" + targetDir + "/" + fileinfo.Name + "成功." ); 86 ftp = null; 87 88 #region 89 /***** 90 *FtpWebResponse 91 * ****/ 92 //FtpWebResponse ftpWebResponse = (FtpWebResponse)ftp.GetResponse(); 93 #endregion 94 } 95 96 private static FtpWebRequest GetRequest(string URI, string username, string password) 97 { 98 //根據服務器信息FtpWebRequest創建類的對象 99 FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(URI); 100 //提供身份驗證信息 101 result.Credentials = new System.Net.NetworkCredential(username, password); 102 //設置請求完成之後是否保持到FTP服務器的控制連接,默認值為true 103 result.KeepAlive = false; 104 return result; 105 }