实现断点续传的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.lang.Process类
一.概述 Process类是一个抽象类(所有的方法均是抽象的),封装了一个进程(即一个执行程序). Process 类提供了执行从进程输入.执行输出到进程.等待进程完成.检查进程的 ...
- spring3种配置的比较
引用自:Spring 3.x 企业应用开发实战
- 为现有图像处理程序添加读写exif的功能
为现有图像处理程序添加读取exif的功能 exif是图片的重要参数,在使用过程中很关键的一点是exif的数据能够和图片一起存在.exif的相关功能在操作系统中就集成了,在csharp中也似乎有了实现. ...
- 财务报表 > 现金流表的直接法,间接法,Cash Flow from Operating Activites
经营活动现金流量 Cash Flow from Operating Activites 是指企业投资活动和筹资活动以外的所有的交易和事项产生的现金流量.它是企业现金的主要来源. 1. 直接法经营活动现 ...
- 连接MySQL错误:Can't connect to MySQL server (10060)
问题原因: 导致些问题可能有以下几个原因: 1.网络不通: 2.服务未启动: 3.防火墙端口未开放: ----防火墙端口未开放的可能性比较大
- DP4J -- mnist
标签(空格分隔): DeepLearning mnist mnist是一个数据集,其中包含很多手写数字的图片,每张图片都已经打上了label: Deep Learning 传统的机器学习神经网络由一层 ...
- ChartControl 折线图 柱状图
添加折线图(柱状图) 拖动ChartControl到Form上 在Series Collection中添加Line(或Bar) DevExpress.XtraCharts.Series series1 ...
- 微信小程序-视图模板
定义模板 使用name属性,作为模板的名字.然后在<template/>内定义代码片段,如: <!-- index: int msg: string time: string --& ...
- Javascript运用函数计算正方形的面积
<html> <head> <meta http-equiv="Content-Type" content="text/html; char ...
- Scrum Meeting 14-20151227
说明 这几天我们代码人员一直在做数据库,没有来得及更新博客,从明天开始将会正常做scrum meeting,也将加快开发 工作,预计beta版本将会在12.30之前发布. 摘要 目前基本开发都已经做的 ...