C# -- FTP上传下载
C# -- FTP上传下载
1. C#实现FTP下载
private static void TestFtpDownloadFile(string strFtpPath, string strFileName, string strFtpUser, string strFtpPassWord, string strSaveFileName) { FtpWebRequest ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(strFtpPath + strFileName); ftpWebRequest.Credentials = new System.Net.NetworkCredential(strFtpUser, strFtpPassWord); ftpWebRequest.UseBinary = true; ftpWebRequest.UsePassive = true; ftpWebRequest.KeepAlive = true; ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile; FtpWebResponse ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse(); Stream ftpStream = ftpWebResponse.GetResponseStream(); FileStream localFileStream = new FileStream(strSaveFileName, FileMode.Create); int bufferSize = 1 * 1024 * 1024; byte[] byteBuffer = new byte[bufferSize]; int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize); try { while (bytesRead > 0) { localFileStream.Write(byteBuffer, 0, bytesRead); bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } localFileStream.Close(); ftpStream.Close(); ftpWebResponse.Close(); ftpWebRequest = null; Console.WriteLine("下载完成 "); }
2. C#实现FTP上传
private static void TestFtpUploadFile(string strFtpPath, string strFileName, string strFtpUser, string strFtpPassWord, string strUploadFileName) { FileInfo uploadFileInfo = new FileInfo(strUploadFileName); FtpWebRequest ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(strFtpPath + strFileName); ftpWebRequest.UseBinary = true; ftpWebRequest.Credentials = new NetworkCredential(strFtpUser, strFtpPassWord); ftpWebRequest.KeepAlive = false; ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile; ftpWebRequest.ContentLength = uploadFileInfo.Length; Stream ftpStream = ftpWebRequest.GetRequestStream(); FileStream uploadFileReadStream = uploadFileInfo.OpenRead(); int bufferSize = 1 * 1024 * 1024; byte[] byteBuffer = new byte[bufferSize]; int bytesRead = uploadFileReadStream.Read(byteBuffer, 0, bufferSize); try { while (bytesRead > 0) { ftpStream.Write(byteBuffer, 0, bytesRead); bytesRead = uploadFileReadStream.Read(byteBuffer, 0, bufferSize); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } ftpStream.Close(); uploadFileReadStream.Close(); ftpWebRequest = null; Console.WriteLine("上传完成 "); }