c# ftp递归下载文件,找来找去这个最好。(打断点,一小处foreach要改成for)

 /// <summary>
/// ftp文件上传、下载操作类
/// </summary>
public class FTPHelper
{ /// <summary>
/// ftp用户名,匿名为“”
/// </summary>
private string ftpUser; /// <summary>
/// ftp用户密码,匿名为“”
/// </summary>
private string ftpPassWord; /// <summary>
///通过用户名,密码连接到FTP服务器
/// </summary>
/// <param name="ftpUser">ftp用户名,匿名为“”</param>
/// <param name="ftpPassWord">ftp登陆密码,匿名为“”</param>
public FTPHelper(string ftpUser, string ftpPassWord)
{
this.ftpUser = ftpUser;
this.ftpPassWord = ftpPassWord;
} /// <summary>
/// 匿名访问
/// </summary>
public FTPHelper()
{
this.ftpUser = "";
this.ftpPassWord = "";
} /// <summary>
/// 上传文件到Ftp服务器
/// </summary>
/// <param name="uri">把上传的文件保存为ftp服务器文件的uri,如"ftp://192.168.1.104/capture-212.avi"</param>
/// <param name="upLoadFile">要上传的本地的文件路径,如D:\capture-2.avi</param>
public void UpLoadFile(string UpLoadUri, string upLoadFile)
{
Stream requestStream = null;
FileStream fileStream = null;
FtpWebResponse uploadResponse = null; try
{
Uri uri = new Uri(UpLoadUri); FtpWebRequest uploadRequest = (FtpWebRequest)WebRequest.Create(uri);
uploadRequest.Method = WebRequestMethods.Ftp.UploadFile; uploadRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord); requestStream = uploadRequest.GetRequestStream();
fileStream = File.Open(upLoadFile, FileMode.Open); byte[] buffer = new byte[];
int bytesRead;
while (true)
{
bytesRead = fileStream.Read(buffer, , buffer.Length);
if (bytesRead == )
break;
requestStream.Write(buffer, , bytesRead);
} requestStream.Close(); uploadResponse = (FtpWebResponse)uploadRequest.GetResponse(); }
catch (Exception ex)
{
throw new Exception("上传文件到ftp服务器出错,文件名:" + upLoadFile + "异常信息:" + ex.ToString());
}
finally
{
if (uploadResponse != null)
uploadResponse.Close();
if (fileStream != null)
fileStream.Close();
if (requestStream != null)
requestStream.Close();
}
} /// <summary>
/// 从ftp下载文件到本地服务器
/// </summary>
/// <param name="downloadUrl">要下载的ftp文件路径,如ftp://192.168.1.104/capture-2.avi</param>
/// <param name="saveFileUrl">本地保存文件的路径,如(@"d:\capture-22.avi"</param>
public void DownLoadFile(string downloadUrl, string saveFileUrl)
{
Stream responseStream = null;
FileStream fileStream = null;
StreamReader reader = null; try
{
// string downloadUrl = "ftp://192.168.1.104/capture-2.avi"; FtpWebRequest downloadRequest = (FtpWebRequest)WebRequest.Create(downloadUrl);
downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile; //string ftpUser = "yoyo";
//string ftpPassWord = "123456";
downloadRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord); FtpWebResponse downloadResponse = (FtpWebResponse)downloadRequest.GetResponse();
responseStream = downloadResponse.GetResponseStream(); fileStream = File.Create(saveFileUrl);
byte[] buffer = new byte[];
int bytesRead;
while (true)
{
bytesRead = responseStream.Read(buffer, , buffer.Length);
if (bytesRead == )
break;
fileStream.Write(buffer, , bytesRead);
}
}
catch (Exception ex)
{
throw new Exception("从ftp服务器下载文件出错,文件名:" + downloadUrl + "异常信息:" + ex.ToString());
}
finally
{
if (reader != null)
{
reader.Close();
}
if (responseStream != null)
{
responseStream.Close();
}
if (fileStream != null)
{
fileStream.Close();
}
}
} /// <summary>
/// 从FTP下载文件到本地服务器,支持断点下载
/// </summary>
/// <param name="ftpUri">ftp文件路径,如"ftp://localhost/test.txt"</param>
/// <param name="saveFile">保存文件的路径,如C:\\test.txt</param>
public void BreakPointDownLoadFile(string ftpUri, string saveFile)
{
System.IO.FileStream fs = null;
System.Net.FtpWebResponse ftpRes = null;
System.IO.Stream resStrm = null;
try
{
//下载文件的URI
Uri u = new Uri(ftpUri);
//设定下载文件的保存路径
string downFile = saveFile; //FtpWebRequest的作成
System.Net.FtpWebRequest ftpReq = (System.Net.FtpWebRequest)
System.Net.WebRequest.Create(u);
//设定用户名和密码
ftpReq.Credentials = new System.Net.NetworkCredential(ftpUser, ftpPassWord);
//MethodにWebRequestMethods.Ftp.DownloadFile("RETR")设定
ftpReq.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
//要求终了后关闭连接
ftpReq.KeepAlive = false;
//使用ASCII方式传送
ftpReq.UseBinary = false;
//设定PASSIVE方式无效
ftpReq.UsePassive = false; //判断是否继续下载
//继续写入下载文件的FileStream if (System.IO.File.Exists(downFile))
{
//继续下载
ftpReq.ContentOffset = (new System.IO.FileInfo(downFile)).Length;
fs = new System.IO.FileStream(
downFile, System.IO.FileMode.Append, System.IO.FileAccess.Write);
}
else
{
//一般下载
fs = new System.IO.FileStream(
downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);
} //取得FtpWebResponse
ftpRes = (System.Net.FtpWebResponse)ftpReq.GetResponse();
//为了下载文件取得Stream
resStrm = ftpRes.GetResponseStream();
//写入下载的数据
byte[] buffer = new byte[];
while (true)
{
int readSize = resStrm.Read(buffer, , buffer.Length);
if (readSize == )
break;
fs.Write(buffer, , readSize);
}
}
catch (Exception ex)
{
throw new Exception("从ftp服务器下载文件出错,文件名:" + ftpUri + "异常信息:" + ex.ToString());
}
finally
{
fs.Close();
resStrm.Close();
ftpRes.Close();
}
} #region 从FTP上下载整个文件夹,包括文件夹下的文件和文件夹 /// <summary>
/// 列出FTP服务器上面当前目录的所有文件和目录
/// </summary>
/// <param name="ftpUri">FTP目录</param>
/// <returns></returns>
public List<FileStruct> ListFilesAndDirectories(string ftpUri)
{
WebResponse webresp = null;
StreamReader ftpFileListReader = null;
FtpWebRequest ftpRequest = null;
try
{
ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpUri));
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
ftpRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);
webresp = ftpRequest.GetResponse();
ftpFileListReader = new StreamReader(webresp.GetResponseStream(), Encoding.Default);
}
catch (Exception ex)
{
throw new Exception("获取文件列表出错,错误信息如下:" + ex.ToString());
}
string Datastring = ftpFileListReader.ReadToEnd();
return GetList(Datastring); } /// <summary>
/// 列出FTP目录下的所有文件
/// </summary>
/// <param name="ftpUri">FTP目录</param>
/// <returns></returns>
public List<FileStruct> ListFiles(string ftpUri)
{
List<FileStruct> listAll = ListFilesAndDirectories(ftpUri);
List<FileStruct> listFile = new List<FileStruct>();
foreach (FileStruct file in listAll)
{
if (!file.IsDirectory)
{
listFile.Add(file);
}
}
return listFile;
} /// <summary>
/// 列出FTP目录下的所有目录
/// </summary>
/// <param name="ftpUri">FRTP目录</param>
/// <returns>目录列表</returns>
public List<FileStruct> ListDirectories(string ftpUri)
{
List<FileStruct> listAll = ListFilesAndDirectories(ftpUri);
List<FileStruct> listDirectory = new List<FileStruct>();
foreach (FileStruct file in listAll)
{
if (file.IsDirectory)
{
listDirectory.Add(file);
}
}
return listDirectory;
} /// <summary>
/// 获得文件和目录列表
/// </summary>
/// <param name="datastring">FTP返回的列表字符信息</param>
private List<FileStruct> GetList(string datastring)
{
List<FileStruct> myListArray = new List<FileStruct>();
string[] dataRecords = datastring.Split('\n');
FileListStyle _directoryListStyle = GuessFileListStyle(dataRecords);
foreach (string s in dataRecords)
{
if (_directoryListStyle != FileListStyle.Unknown && s != "")
{
FileStruct f = new FileStruct();
f.Name = "..";
switch (_directoryListStyle)
{
case FileListStyle.UnixStyle:
f = ParseFileStructFromUnixStyleRecord(s);
break;
case FileListStyle.WindowsStyle:
f = ParseFileStructFromWindowsStyleRecord(s);
break;
}
if (!(f.Name == "." || f.Name == ".."))
{
myListArray.Add(f);
}
}
}
return myListArray;
}
/// <summary>
/// 从Unix格式中返回文件信息
/// </summary>
/// <param name="Record">文件信息</param>
private FileStruct ParseFileStructFromUnixStyleRecord(string Record)
{
FileStruct f = new FileStruct();
string processstr = Record.Trim();
f.Flags = processstr.Substring(, );
f.IsDirectory = (f.Flags[] == 'd');
processstr = (processstr.Substring()).Trim();
_cutSubstringFromStringWithTrim(ref processstr, ' ', ); //跳过一部分
f.Owner = _cutSubstringFromStringWithTrim(ref processstr, ' ', );
f.Group = _cutSubstringFromStringWithTrim(ref processstr, ' ', );
_cutSubstringFromStringWithTrim(ref processstr, ' ', ); //跳过一部分
string yearOrTime = processstr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[];
if (yearOrTime.IndexOf(":") >= ) //time
{
processstr = processstr.Replace(yearOrTime, DateTime.Now.Year.ToString());
}
f.CreateTime = DateTime.Parse(_cutSubstringFromStringWithTrim(ref processstr, ' ', ));
f.Name = processstr; //最后就是名称
return f;
} /// <summary>
/// 从Windows格式中返回文件信息
/// </summary>
/// <param name="Record">文件信息</param>
private FileStruct ParseFileStructFromWindowsStyleRecord(string Record)
{
FileStruct f = new FileStruct();
string processstr = Record.Trim();
string dateStr = processstr.Substring(, );
processstr = (processstr.Substring(, processstr.Length - )).Trim();
string timeStr = processstr.Substring(, );
processstr = (processstr.Substring(, processstr.Length - )).Trim();
DateTimeFormatInfo myDTFI = new CultureInfo("en-US", false).DateTimeFormat;
myDTFI.ShortTimePattern = "t";
f.CreateTime = DateTime.Parse(dateStr + " " + timeStr, myDTFI);
if (processstr.Substring(, ) == "<DIR>")
{
f.IsDirectory = true;
processstr = (processstr.Substring(, processstr.Length - )).Trim();
}
else
{
string[] strs = processstr.Split(new char[] { ' ' },);// StringSplitOptions.RemoveEmptyEntries); // true);
processstr = strs[];
f.IsDirectory = false;
}
f.Name = processstr;
return f;
}
/// <summary>
/// 按照一定的规则进行字符串截取
/// </summary>
/// <param name="s">截取的字符串</param>
/// <param name="c">查找的字符</param>
/// <param name="startIndex">查找的位置</param>
private string _cutSubstringFromStringWithTrim(ref string s, char c, int startIndex)
{
int pos1 = s.IndexOf(c, startIndex);
string retString = s.Substring(, pos1);
s = (s.Substring(pos1)).Trim();
return retString;
}
/// <summary>
/// 判断文件列表的方式Window方式还是Unix方式
/// </summary>
/// <param name="recordList">文件信息列表</param>
private FileListStyle GuessFileListStyle(string[] recordList)
{
foreach (string s in recordList)
{
if (s.Length >
&& Regex.IsMatch(s.Substring(, ), "(-|d)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)"))
{
return FileListStyle.UnixStyle;
}
else if (s.Length >
&& Regex.IsMatch(s.Substring(, ), "[0-9][0-9]-[0-9][0-9]-[0-9][0-9]"))
{
return FileListStyle.WindowsStyle;
}
}
return FileListStyle.Unknown;
} /// <summary>
/// 从FTP下载整个文件夹
/// </summary>
/// <param name="ftpDir">FTP文件夹路径</param>
/// <param name="saveDir">保存的本地文件夹路径</param>
public void DownFtpDir(string ftpDir, string saveDir)
{
List<FileStruct> files = ListFilesAndDirectories(ftpDir);
if (!Directory.Exists(saveDir))
{
Directory.CreateDirectory(saveDir);
}
foreach (FileStruct f in files)
{
if (f.IsDirectory) //文件夹,递归查询
{
DownFtpDir(ftpDir + "/" + f.Name, saveDir + "\\" + f.Name);
}
else //文件,直接下载
{
DownLoadFile(ftpDir + "/" + f.Name, saveDir + "\\" + f.Name);
}
}
} #endregion
} #region 文件信息结构
public struct FileStruct
{
public string Flags;
public string Owner;
public string Group;
public bool IsDirectory;
public DateTime CreateTime;
public string Name;
}
public enum FileListStyle
{
UnixStyle,
WindowsStyle,
Unknown
}
#endregion

C#- FTP递归下载文件的更多相关文章

  1. 【FTP】C# System.Net.FtpClient库连接ftp服务器(下载文件)

    如果自己单枪匹马写一个连接ftp服务器代码那是相当恐怖的(socket通信),有一个评价较高的dll库可以供我们使用. 那就是System.Net.FtpClient,链接地址:https://net ...

  2. (4)FTP服务器下载文件

    上一篇中,我们提到了怎么从FTP服务器下载文件.现在来具体讲述一下. 首先是路径配置.. 所以此处我们需要一个app.config来设置路径. <?xml version="1.0&q ...

  3. 通过cmd命令到ftp上下载文件

    通过cmd命令到ftp上下载文件 点击"开始"菜单.然后输入"cmd"点"enter"键,出现cmd命令执行框 2 输入"ftp& ...

  4. Python之FTP多线程下载文件之分块多线程文件合并

    Python之FTP多线程下载文件之分块多线程文件合并 欢迎大家阅读Python之FTP多线程下载系列之二:Python之FTP多线程下载文件之分块多线程文件合并,本系列的第一篇:Python之FTP ...

  5. Python之FTP多线程下载文件之多线程分块下载文件

    Python之FTP多线程下载文件之多线程分块下载文件 Python中的ftplib模块用于对FTP的相关操作,常见的如下载,上传等.使用python从FTP下载较大的文件时,往往比较耗时,如何提高从 ...

  6. 访问FTP站点下载文件,提示“当前的安全设置不允许从该位置下载文件”的解决方案

    访问FTP站点下载文件,提示“当前的安全设置不允许从该位置下载文件”的解决方案: 打开客戶端浏览器--工具---internet-安全-自定义级别-选择到低到中低. 然后点受信任站点,把你要访问的站点 ...

  7. linux FTP 批量下载文件

    wget是一个从网络上自动下载文件的自由工具,支持通过HTTP.HTTPS.FTP三个最常见的TCP/IP协议下载,并可以使用HTTP代理.wget名称的由来是“World Wide Web”与“ge ...

  8. ftp自动上传下载文件脚本

    FTP自动登录批量下载文件 从ftp服务器192.168.1.60 上的/home/data 到本地的/home/databackup目录 #!/bin/bash ftp -v -n 192.168. ...

  9. AWS S3 递归上传文件和递归下载文件, 以及S3之间拷贝文件夹

    1. 递归上传文件: aws s3 cp 本地文件夹 s3://bucket-name -- recursive --region us-east-1 2. 递归下载S3上的文件夹: cd  本地下载 ...

随机推荐

  1. 使用Yeoman搭建 AngularJS 应用 (3) —— 让我们搭建一个网页应用

    原文地址:http://yeoman.io/codelab/setup.html 与Yeoman的交互大多数是通过命令行.在苹果机器需要使用Terminal应用,在Linux使用shell.如果使用W ...

  2. Delphi XE5 android 图解为Android应用制作签名

    本文摘自 http://redboy136.blog.163.com/blog/static/107188432201381872820132 要发布android应用,必须做签名的.看一下具体的操作 ...

  3. sjtu1313 太湖旅行

    Description 西山风景区是苏州著名的国家级风景区,一到暑假,游客们都蜂拥而至.作为太湖风景区的精华,西山景区吸引人的地方主要在它的群岛风光.花果丛林和名胜古迹. ginrat对这个地方向往已 ...

  4. ZOJ 3713 In 7-bit

    点我看题目 题意 : 这个题的英文叙述真的是太强了,真不知道哪里来的英文,完全看不懂,看了两个小时没弄懂真正的题意.就是给你一个字符串,先输出长度,但是长度要用二进制表示出来,二进制的低7位左边如果没 ...

  5. Mpeg-2的同步及时间恢复--STC,PCR,DTS,PTS

    http://blog.csdn.net/hice1226/article/details/6717354 Mpeg-2的同步及时间恢复--STC,PCR,DTS,PTS 摘要:Mpeg-2同步及时间 ...

  6. Document字段发生变化后,报的错

    2016-10-11 15:27:47,828 [ERROR] [main] SpringApplication:838 - Application startup failedorg.springf ...

  7. JAVA实现word doc docx pdf excel的在线浏览 - 仿百度文库 源码

    我们具体实现思路是这样的 首先下载并安装openoffice和swftools openoffice下载地址:http://www.openoffice.org/download/index.html ...

  8. 用if else 判断是不是7的倍数等

    static void Main(string[] args)        {            while (true)            {                int b; ...

  9. NOI 2014 感想

    NOI2014结束了,我卡线登上了领奖台... 这是我第一次NOI,我觉得我收获了很多东西: 1.考前心态不重要,重要的是实力 真正考试的时候是顾不得想其他事情的 2.测试数据是人出的!不是随机的!不 ...

  10. Shell获取文件后缀名

    file = "thisfile.txt" echo "filename: ${file%.*}" echo "extension: ${file## ...