C# FTPWebRequest、FTPWebResponse
透過FTPWebRequest、FTPWebResponse來下載FPT上的指定檔案
string ftpURL = "ftp://192.168.100.1:21/";
string ftpUserID = "ftpUser";
string ftpUserPWD = "abcdefg";
string ftpFilePath = ftpURL + "FileName.xls";
string tempStoragePath = AppDomain.CurrentDomain.BaseDirectory + "FtpFileStorage\\FileName.xls";;
//FtpWebRequest
FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(ftpFilePath);
NetworkCredential ftpCredential = new NetworkCredential(ftpUserID, ftpUserPWD);
ftpRequest.Credentials = ftpCredential;
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
//FtpWebResponse
FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
//Get Stream From FtpWebResponse
Stream ftpStream = ftpResponse.GetResponseStream();
using (FileStream fileStream = new FileStream(tempStoragePath, FileMode.Create))
{
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
fileStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
}
ftpStream.Close();
ftpResponse.Close();
下載後得到Stream,再透過FileStream寫入到指定路徑