1 // FTP 下载 2 private int FtpFileDownload(string savePath, string fileName, string ftpServerIP, string ftpUserID, string ftpPassword) 3 { 4 5 string ftpServerPath = "ftp://" + ftpServerIP + ":23" + fileName; //":23"指定的端口,不填默认端口为21 6 string ftpUser = ftpUserID; 7 string ftpPwd = ftpPassword; 8 string saveFilePath = savePath; 9 10 FileStream outputStream = null; 11 FtpWebResponse response = null; 12 FtpWebRequest reqFTP; 13 14 try 15 { 16 outputStream = new FileStream(saveFilePath, FileMode.Create); 17 18 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerPath)); 19 reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; 20 reqFTP.UseBinary = true; 21 reqFTP.KeepAlive = false; 22 reqFTP.Timeout = 3000; 23 reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd); 24 response = (FtpWebResponse)reqFTP.GetResponse(); 25 Stream ftpStream = response.GetResponseStream(); 26 int bufferSize = 2048; 27 int readCount; 28 ftpFileReadSize = 0; 29 byte[] buffer = new byte[bufferSize]; 30 31 readCount = ftpStream.Read(buffer, 0, bufferSize); 32 while (readCount > 0) 33 { 34 ftpFileReadSize += readCount; 35 outputStream.Write(buffer, 0, readCount); 36 readCount = ftpStream.Read(buffer, 0, bufferSize); 37 } 38 39 ftpStream.Close(); 40 outputStream.Close(); 41 response.Close(); 42 } 43 catch (Exception ex) 44 { 45 Trace.WriteLine("FtpClient异常:" + ex.Message); 46 if (outputStream != null) 47 { 48 outputStream.Close(); 49 } 50 if (response != null) 51 { 52 response.Close(); 53 } 54 55 return -1; 56 } 57 58 return 0; 59 } 60 61 // 获取FTP文件大小 62 private long GetFtpFileSize(string fileName, string ftpServerIP, string ftpUserID, string ftpPassword) 63 { 64 long fileSize = 0; 65 string ftpServerPath = "ftp://" + ftpServerIP + ":23" + fileName; 66 string ftpUser = ftpUserID; 67 string ftpPwd = ftpPassword; 68 69 FtpWebResponse response = null; 70 FtpWebRequest reqFTP; 71 72 try 73 { 74 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerPath)); 75 reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; 76 reqFTP.UseBinary = true; 77 reqFTP.KeepAlive = false; 78 reqFTP.Timeout = 3000; 79 reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd); 80 reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;//要求返回文件大小属性 81 response = (FtpWebResponse)reqFTP.GetResponse(); 82 fileSize = response.ContentLength; 83 response.Close(); 84 } 85 catch (Exception ex) 86 { 87 Trace.WriteLine("FtpClient异常:" + ex.Message); 88 if (response != null) 89 { 90 response.Close(); 91 } 92 93 return -1; 94 } 95 96 return fileSize; 97 } 98