实现断点续传的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 多线程下载文件并实时计算下载百分比(断点续传)
多线程下载文件 多线程同时下载文件即:在同一时间内通过多个线程对同一个请求地址发起多个请求,将需要下载的数据分割成多个部分,同时下载,每个线程只负责下载其中的一部分,最后将每一个线程下载的部分组装起来 ...
随机推荐
- iOS 解决图片上传到服务器旋转90度的问题(图片倒置)
//使用swift的朋友们可以,把这个所在的类的.h,在-Header-Swift.h中一用一下. - (UIImage *)fixOrientation:(UIImage *)aImage { if ...
- 使用jquery-qrcode生成二维码
一.使用jquery-qrcode生成二维码 先简单说一下jquery-qrcode,这个开源的三方库(可以从https://github.com/jeromeetienne/jquery-qrcod ...
- 搭建基于Jenkins salt-api的运维工具
1. 安装salt-master和salt-minion 安装过程不再赘述,请参考http://docs.saltstack.com/en/latest/topics/installation/ind ...
- Linux_用户级_常用命令(3):mkdir
Linux常用命令之mkdir 开篇语:懒是人类进步的源动力 本文原创,专为光荣之路公众号所有,欢迎转发,但转发请务必写出处! Linux常用命令第3集包含命令:mkdir (附赠tree命令,日期时 ...
- javascript - 可编辑表格控件 支持全键盘操作(无JS框架)
项目中经常会用到表格编辑控件,网上也有不少,但是确实没有完全符合我要求的, 自己写一个吧! 1.该控件支持 数据显示列,文本编辑列,选择列,下拉列,索引列,删除列 六种列类型 2.支持全键盘操作,自定 ...
- 学习Git的总结与体会
学习Git的总结 blog 第一次学习Git是完全按照廖雪峰老师的教程学习的,学的过程中基本上没有遇到什么问题,但是自己实际操作就问题不断了. 首先,还是按照惯例,来膜拜一下廖雪峰老师精简的教程知识吧 ...
- javascript数据属性和访问器属性
var book={ _year:2004, edition:1};Object.defineProperty(book,"year",{ get:function(){ retu ...
- [TCPIP] IP路由表及选路 Note
TCP/IP IP路由表及选路 1.路由表信息 路由表一般包含信息:目的IP地址.下一站路由器的IP地址.标志. 为数据报传送指定的一个网络接口. 查看路由表信息mac-abeen:~ abeen$ ...
- git 设置不需要输入密码
https方式每次都要输入密码,按照如下设置即可输入一次就不用再手输入密码的困扰而且又享受https带来的极速 设置记住密码(默认15分钟): git config --global credenti ...
- 【前端】JSON.stringfy 和 JSON.parse(待续)
JSON.stringfy 和 JSON.parse(待续) 支持全局对象JSON的浏览器有:IE8+, FireFox3.5+, Safari4+, Chrome, Opera10.5+ JSON. ...