C# -- FTP上传下载

时间:2023-07-21 11:38:02

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 = * * ; byte[] byteBuffer = new byte[bufferSize];
int bytesRead = ftpStream.Read(byteBuffer, , bufferSize);
try
{
while (bytesRead > )
{
localFileStream.Write(byteBuffer, , bytesRead);
bytesRead = ftpStream.Read(byteBuffer, , 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 = * * ; byte[] byteBuffer = new byte[bufferSize];
int bytesRead = uploadFileReadStream.Read(byteBuffer, , bufferSize);
try
{
while (bytesRead > )
{
ftpStream.Write(byteBuffer, , bytesRead);
bytesRead = uploadFileReadStream.Read(byteBuffer, , bufferSize);
}
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); } ftpStream.Close();
uploadFileReadStream.Close();
ftpWebRequest = null; Console.WriteLine("上传完成 ");
}