private string ftpServerIP = "服務器ip";//服務器ip private string ftpUserID = "ftp的用戶名";//用戶名 private string ftpPassword = "ftp的密碼";//密碼 //filename 為本地文件的絕對路徑 //serverDir為服務器上的目錄 private void Upload(string filename,string serverDir) { FileInfo fileInf = new FileInfo(filename); string uri = string.Format("ftp://{0}/{1}/{2}", ftpServerIP,serverDir,fileInf.Name); FtpWebRequest reqFTP; // 根據uri創建FtpWebRequest對象 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); // ftp用戶名和密碼 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); // 默認為true,連接不會被關閉 // 在一個命令之后被執行 reqFTP.KeepAlive = false; // 指定執行什么命令 reqFTP.Method = WebRequestMethods.Ftp.UploadFile; // 指定數據傳輸類型 reqFTP.UseBinary = true; // 上傳文件時通知服務器文件的大小 reqFTP.ContentLength = fileInf.Length; // 緩沖大小設置為2kb int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; // 打開一個文件流 (System.IO.FileStream) 去讀上傳的文件 FileStream fs = fileInf.OpenRead(); try { // 把上傳的文件寫入流 Stream strm = reqFTP.GetRequestStream(); // 每次讀文件流的2kb contentLen = fs.Read(buff, 0, buffLength); // 流內容沒有結束 while (contentLen != 0) { // 把內容從file stream 寫入 upload stream strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } // 關閉兩個流 strm.Close(); fs.Close(); } catch (Exception ex) { // MessageBox.Show(ex.Message, "Upload Error"); Response.Write("Upload Error:" + ex.Message); } } 調用方法 string filename = "D:\\test.txt"; //本地文件,需要上傳的文件 string serverDir = "img"; //上傳到服務器的目錄,必須存在 Upload (filename,serverDir);
