using System.Net;
public void Download( string fileName)//ftp默認路徑下文件名與本機保存文件名一致
{
FtpWebRequest reqFTP;
try
{
string filePath = @"E:\ftpDownload";//本機保存路徑
FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;//指定當前請求是什麼命令(upload,download,filelist等)
reqFTP.UseBinary = true;//指定文件傳輸的類型
reqFTP.Credentials = new NetworkCredential(username, password); //指定登錄ftp服務器的用戶名和密碼。
reqFTP.KeepAlive = true;//指定在請求完成之後是否關閉到 FTP 服務器的控制連接
reqFTP.UsePassive = false;//指定使用主動模式還是被動模式
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
throw ex;
}
}
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();報錯遠程服務器返回錯誤:(550)文件不可用(例如,未找到文件,無法訪問文件)的解決方法:問題可能是uri格式不正確;也有可能是FTP文件權限問題;ftp賬號只執行到默認路徑下的文件;默認路徑下的文件夾可能操作讀取權限有問題,無法讀取。注意ftp默認路徑