提供一个helper类,从FTP服务器下载文件到本地
public class FTPHelper
{
public static FtpFileInfo[] GetFtpFileInfos(string ftpPath, string userName, string passWord)
{
LinkedList<FtpFileInfo> linkedList = new LinkedList<FtpFileInfo>();
var reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
reqFtp.UsePassive = false;
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(userName, passWord);
reqFtp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
var response = (FtpWebResponse)reqFtp.GetResponse();
var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string fileDetail = reader.ReadLine();
while (fileDetail != null)
{
linkedList.AddLast(new FtpFileInfo(fileDetail));
fileDetail = reader.ReadLine();
}
reader.Close();
response.Close();
return linkedList.ToArray();
}
/// <summary>
/// 从ftp下载文件夹到本地
/// </summary>
/// <param name="sourceDirectoryPath">源数据文件夹地址(备注:结尾不要“/”)</param>
/// <param name="targetDirectoryPath">目标数据文件夹地址(备注:结尾不要“/”)</param>
/// <param name="username">用户名</param>
/// <param name="password">密码</param>
public static bool DownLoadDirectory(string sourceDirectoryPath, string targetDirectoryPath, string username, string password)
{
try
{
var ftpFileInfos = GetFtpFileInfos(sourceDirectoryPath, username, password);
if (ftpFileInfos != null && ftpFileInfos.Count() > 0)
{
foreach (var file in ftpFileInfos)
{
string fullSourcePath = sourceDirectoryPath + "/" + file.FileName;
string fullTargetPath = targetDirectoryPath + "/" + file.FileName;
if (file.UnixFileType == "d")
{
if (!string.IsNullOrEmpty(file.FileName.Replace(".", "")))
{
DownLoadDirectory(fullSourcePath, fullTargetPath, username, password);
}
}
else
{
DownLoadFile(fullSourcePath, targetDirectoryPath, username, password);
}
}
}
return true;
}catch
{
return false;
}
}
/// <summary>
/// 从ftp下载文件到本地文件夹
/// </summary>
/// <param name="fullSourcePath">ftp文件完整地址</param>
/// <param name="targetDirectoryPath">目标文件夹路径</param>
/// <param name="username">用户名</param>
/// <param name="password">密码</param>
public static void DownLoadFile(string