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默认路径