实现断点续传的FTP下载类(支持多线程多任务下载)
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.IO;
using System.Net; namespace RSGIS.FTPClient
{ public class MultiFtpService
{
#region variable private string _Server;//服务器地址
private string _UserName;//用户名
private string _Password;//密码
private string _FileUrl;//文件地址
private string _SavePath;//保存路经
Thread _Thread;
private int _TaskIndex;
private int _ThreadIndex; private int FileSpeed; // 实时下载速度 private FtpWebRequest ftpRequest = null;
private FtpWebResponse ftpResponse = null;
private Stream ftpStream = null;
private int bufferSize = 2048;
private int highestPercentageReached = 0; public delegate void DelegateDisplayProgress(int taskindex, int progress);
public DelegateDisplayProgress WorkMethod; public delegate void DelegateDisplayFileSpeed(int taskindex, string speed);
public DelegateDisplayFileSpeed FileSpeedMethod; #endregion #region Constructor public MultiFtpService(string server, string username, string password, int taskIndex, int threadIndex, string fileUrl, string savePath)
{
_Server = server;
_UserName = username;
_Password = password;
_FileUrl = fileUrl;
_SavePath = savePath;
_TaskIndex = taskIndex;
_ThreadIndex = threadIndex;
} #endregion #region Functions
//开始
public void Start()
{
long fileSize = GetLength();
_Thread = new Thread(() => { TheadDownload(_FileUrl, _SavePath, _TaskIndex, _ThreadIndex, fileSize); });
_Thread.Start();
}
/// <summary>
/// 暂停线程
/// </summary>
public void Stop()
{
_Thread.Suspend();
}
// 恢复线程
public void continues()
{
_Thread.Resume();
}
//获取文件长度
private long GetLength()
{
Ftp ftpclient = new Ftp(_Server, _UserName, _Password);
long fileSize = ftpclient.getFileSize(_FileUrl);
ftpclient = null;
return fileSize;
}
/// <summary>
/// 下载
/// </summary>
/// <param name="remoteFile"></param>
/// <param name="localFile"></param>
/// <param name="taskindex"></param>
/// <param name="threadindex"></param>
/// <param name="fileSize"></param>
private void TheadDownload(string remoteFile, string localFile, int taskindex, int threadindex, long fileSize)
{
try
{
//续传
if (File.Exists(localFile))
{
FileInfo file = new FileInfo(localFile);
int locSize = Convert.ToInt32(file.Length);
if (locSize.ToString() != fileSize.ToString())
{
Uri FTPUri = new Uri(_Server + "/" + remoteFile);
RestartDownloadFromServer(taskindex, localFile, FTPUri, file.Length, fileSize);
}
}
else
{
// Create Request
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(_Server + "/" + remoteFile);
ftpRequest.Credentials = new NetworkCredential(_UserName, _Password);
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
ftpRequest.Proxy = GlobalProxySelection.GetEmptyWebProxy();
// Request Type
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
// Get Response
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
// Get server response stream
ftpStream = ftpResponse.GetResponseStream();
FileStream localFileStream = new FileStream(localFile, FileMode.Create);
// Buffer for downloaded data
byte[] byteBuffer = new byte[bufferSize];
int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
// Download File
int fileSizes = Convert.ToInt32(fileSize);
try
{
while (bytesRead > 0)
{
localFileStream.Write(byteBuffer, 0, bytesRead);
bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
int Complete = Convert.ToInt32(fileSizes) - bytesRead;
double Fcompletes = Convert.ToDouble(Complete) / Convert.ToDouble(fileSize);
double x = 1;
double Fcomplete = x - Fcompletes;
fileSizes = Complete;
if (Fcomplete * 100 > highestPercentageReached)
{
WorkMethod(taskindex, Convert.ToInt32(Fcomplete * 100));
string speed = SizeConversion(Convert.ToInt64(bytesRead / 0.01));
FileSpeedMethod(taskindex, speed); }
}
FileInfo file = new FileInfo(localFile);
int locSize = Convert.ToInt32(file.Length);
if (locSize.ToString() != fileSizes.ToString())
{
Uri FTPUri = new Uri(_Server + "/" + remoteFile);
RestartDownloadFromServer(taskindex, localFile, FTPUri, file.Length, fileSize);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
localFileStream.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
WorkComplete();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
//catch { }
}
//断点续传
private bool RestartDownloadFromServer(int taskindex, string fileName, Uri serverUri, long offset, long fileSize)
{
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
} // 获取ftp
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Credentials = new NetworkCredential(_UserName, _Password);
request.UseBinary = true;
request.UsePassive = true;
request.KeepAlive = true;
request.Proxy = GlobalProxySelection.GetEmptyWebProxy();
// Request Type
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.ContentOffset = offset;
FtpWebResponse response = null;
try
{
response = (FtpWebResponse)request.GetResponse();
}
catch (WebException e)
{
Console.WriteLine(e.Status);
Console.WriteLine(e.Message);
return false;
}
// 获取流
ftpStream = response.GetResponseStream();
//StreamReader reader = new StreamReader(newFile);
//string newFileData = reader.ReadToEnd();
FileStream localFileStream = new FileStream(fileName, FileMode.Append);
// Buffer for downloaded data
byte[] byteBuffer = new byte[bufferSize];
int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize); // Download File
int fileSizes = Convert.ToInt32(fileSize);
try
{
while (bytesRead > 0)
{
localFileStream.Write(byteBuffer, 0, bytesRead);
bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
int Complete = Convert.ToInt32(fileSizes) - bytesRead;
double Fcompletes = Convert.ToDouble(Complete) / Convert.ToDouble(fileSize);
double x = 1;
double Fcomplete = x - Fcompletes;
fileSizes = Complete;
if (Fcomplete * 100 > highestPercentageReached)
{
Fcomplete = Fcomplete + offset / fileSize;
WorkMethod(taskindex, Convert.ToInt32(Fcomplete * 100));
string speed = SizeConversion(Convert.ToInt64(bytesRead / 0.01));
FileSpeedMethod(taskindex, speed);
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
//关闭流
localFileStream.Close();
ftpStream.Close();
response.Close();
request = null;
WorkComplete();
return true;
}
//完成
public void WorkComplete()
{
MessageBox.Show("文件下载成功", "Success", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
} /// <summary>
/// 文件大小换算
/// </summary>
/// <param name="bytes">文件长度</param>
/// <returns></returns>
private string SizeConversion(long bytes)
{
int unit = 1024;
if (bytes < unit) return bytes + " B";
int exp = (int)(Math.Log(bytes) / Math.Log(unit));
return String.Format("{0:F1} {1}B", bytes / Math.Pow(unit, exp), "KMGTPE"[exp - 1]);
}
#endregion
}
}
实现断点续传的FTP下载类(支持多线程多任务下载)的更多相关文章
- Python之FTP多线程下载文件之多线程分块下载文件
Python之FTP多线程下载文件之多线程分块下载文件 Python中的ftplib模块用于对FTP的相关操作,常见的如下载,上传等.使用python从FTP下载较大的文件时,往往比较耗时,如何提高从 ...
- C#写文本日志帮助类(支持多线程)
代码: using System; using System.Configuration; using System.IO; using System.Threading.Tasks; namespa ...
- C#写文本日志帮助类(支持多线程)改进版(不适用于ASP.NET程序)
由于iis的自动回收机制,不适用于ASP.NET程序 代码: using System; using System.Collections.Concurrent; using System.Confi ...
- ASP.NET文件下载各种方式比较:对性能的影响、对大文件的支持、对断点续传和多线程下载的支持
asp.net里提供了多种方式,从服务器端向客户端写文件流,实现客户端下载文件.这种技术在做防下载系统时比较有用处.主些技术主要有:WriteFile.TransmitFile和BinaryWrite ...
- Java实现多线程下载,支持断点续传
完整代码:https://github.com/iyuanyb/Downloader 多线程下载及断点续传的实现是使用 HTTP/1.1 引入的 Range 请求参数,可以访问Web资源的指定区间的内 ...
- 实现android支持多线程断点续传下载器功能
多线程断点下载流程图: 多线程断点续传下载原理介绍: 在下载的时候多个线程并发可以占用服务器端更多资源,从而加快下载速度手机端下载数据时难免会出现无信号断线.电量不足等情况,所以需要断点续传功能根据下 ...
- 打印 上一主题 下一主题 利用cURL实现单个文件分多段同时下载,支持断点续传(修订版)
利用cURL实现单个文件分多段同时下载,支持断点续传(修订版) [复制链接] 摘自 http://bbs.chinaunix.net/thread-917952-1-1.html 在ubuntu下 ...
- C# http下载(支持断点续传)
分享下项目里面自己封装的一个http下载类 功能如下: 1.支持断点续传 2.下载失败自动重试 3.超时等异常处理 using System; using System.Collections.Gen ...
- java 多线程下载文件并实时计算下载百分比(断点续传)
多线程下载文件 多线程同时下载文件即:在同一时间内通过多个线程对同一个请求地址发起多个请求,将需要下载的数据分割成多个部分,同时下载,每个线程只负责下载其中的一部分,最后将每一个线程下载的部分组装起来 ...
随机推荐
- Java:通过反射复制父类字段到子类。
有些时候需要建立子类继承于父类,尤其是java里面很多类是用mybatis generator生成的.通过父类构造子类,好像很麻烦,要逐个字段进行赋值(反正我没有找到其他好办法). 想到用反射复制的方 ...
- 使用java mail 发送邮件
1.关联jar包: activation.jar mail.jar 2.调用 @Test public void test1() { List<String> imageUrlLi ...
- 关于onethink的迁移站点产生数据库错误
为了支持国产,本人使用了onethink建立了一个自己的站点( 模板世界:www.templatesy.com ),使用至今,虽然碰到了重重困难,还有很多bug,但总算也勉强建了起来. 在近期的一 ...
- Ubuntu14.04_64位使用过程
1. vmware10 下安装 ubuntu(ps:安装过程中还是将磁盘整的更大一些的好,我最开始20G,不够用啊不够用[典型安装就行]) 2. 右上角的圆圈设置--选择system setting- ...
- 1.Linux系统安装
Linux系统安装系统分区(磁盘分区) 主要管理:文件和目录分类:主分区:最多有4个 扩展分区:1个扩展分区 和主分区最多4个 存放逻辑分区 逻辑分区:存放数据 格式化:高级格式化(逻辑格式化) 写入 ...
- [课程设计]Scrum 3.3 多鱼点餐系统开发进度(下单详细信息页面设计)
Scrum 3.3 多鱼点餐系统开发进度(下单详细信息页面设计) 1.团队名称:重案组 2.团队目标:长期经营,积累客户充分准备,伺机而行 3.团队口号:矢志不渝,追求完美 4.团队选题:餐厅到店点 ...
- Swift_2基础
mport Foundation // MARK: - ?和!的区别// ?代表可选类型,实质上是枚举类型,里面有None和Some两种类型,其实nil相当于OPtional.None,如果非nil相 ...
- python 最大公约数
求解两个整数(不能是负数)的最大公约数(要求两数不能同时为0)当两数都是0时,最大公约数为0方式一:穷举法 def GCU(m, n): if not m: return n elif not n: ...
- C#委托,事件理解入门 (译稿)
原文地址:http://www.codeproject.com/Articles/4773/Events-and-Delegates-Simplified 引用翻译地址:http://www.cnbl ...
- BW知识问答锦集
声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...