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下载类(支持多线程多任务下载)的更多相关文章

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

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

  2. C#写文本日志帮助类(支持多线程)

    代码: using System; using System.Configuration; using System.IO; using System.Threading.Tasks; namespa ...

  3. C#写文本日志帮助类(支持多线程)改进版(不适用于ASP.NET程序)

    由于iis的自动回收机制,不适用于ASP.NET程序 代码: using System; using System.Collections.Concurrent; using System.Confi ...

  4. ASP.NET文件下载各种方式比较:对性能的影响、对大文件的支持、对断点续传和多线程下载的支持

    asp.net里提供了多种方式,从服务器端向客户端写文件流,实现客户端下载文件.这种技术在做防下载系统时比较有用处.主些技术主要有:WriteFile.TransmitFile和BinaryWrite ...

  5. Java实现多线程下载,支持断点续传

    完整代码:https://github.com/iyuanyb/Downloader 多线程下载及断点续传的实现是使用 HTTP/1.1 引入的 Range 请求参数,可以访问Web资源的指定区间的内 ...

  6. 实现android支持多线程断点续传下载器功能

    多线程断点下载流程图: 多线程断点续传下载原理介绍: 在下载的时候多个线程并发可以占用服务器端更多资源,从而加快下载速度手机端下载数据时难免会出现无信号断线.电量不足等情况,所以需要断点续传功能根据下 ...

  7. 打印 上一主题 下一主题 利用cURL实现单个文件分多段同时下载,支持断点续传(修订版)

      利用cURL实现单个文件分多段同时下载,支持断点续传(修订版) [复制链接] 摘自 http://bbs.chinaunix.net/thread-917952-1-1.html 在ubuntu下 ...

  8. C# http下载(支持断点续传)

    分享下项目里面自己封装的一个http下载类 功能如下: 1.支持断点续传 2.下载失败自动重试 3.超时等异常处理 using System; using System.Collections.Gen ...

  9. java 多线程下载文件并实时计算下载百分比(断点续传)

    多线程下载文件 多线程同时下载文件即:在同一时间内通过多个线程对同一个请求地址发起多个请求,将需要下载的数据分割成多个部分,同时下载,每个线程只负责下载其中的一部分,最后将每一个线程下载的部分组装起来 ...

随机推荐

  1. maven的搭建

    1.安装JDK. 2.Maven是 Apache 下的一个项目,官网下载 Maven:http://maven.apache.org/download.cgi 系统变量:M2_HOME= G:\vis ...

  2. 我的CSS布局之旅--持续更新

    虽然我也接触前端一年之久了,但是无奈从切图布局下来的经验还真是很不足,因为之前比赛或者是做小项目时全部都是自己负责设计,所以都是编写边设计,哎呀,也是醉了:或者是有模板,然后从人家上面扒拉下来的,真的 ...

  3. python 随机生成固定长度的字串

    from random import Random#随机生成4到20位的用户名def random_username(): username = '' chars = 'AaBbCcDdEeFfGgH ...

  4. Unity LightmapParameters的使用

    Unity5的烘培十分不好用,今天看官方demo时发现可以用LightmapParameters对模型的GI配置进行单独覆写,介绍一下 LightmapParameters可以把全局光照的配置做成预设 ...

  5. Java读取Level-1行情dbf文件极致优化(1)

    最近架构一个项目,实现行情的接入和分发,需要达到极致的低时延特性,这对于证券系统是非常重要的.接入的行情源是可以配置,既可以是Level-1,也可以是Level-2或其他第三方的源.虽然Level-1 ...

  6. msys2安装

    最近在研究编译linux下的软件到windows环境中. 发现了一个比cygwin更好玩的东西,那就是msys2 其实之前也在试玩mingw和mingw64,2016-08-12,当时的最新版本,mi ...

  7. My first python script for work

    I write it yesterday to watch the NE process(rcpfd,cfgd) automatically, then i will write a window t ...

  8. django系列--第一节

    学习前准备 安装必须的学习环境环境(学习前提:python2.7) pip install django==1.8 pip install mysqldb(后面会用) pip install Pill ...

  9. XML特殊符号

    在XML中"<" 字符和"&"字符是严格禁止使用的.要使用这几种字符需要使用它们的实体, 下面是五个在XML文档中预定义好的实体:< < ...

  10. 调用微信JsAPI端获取位置

    public partial class test : BasePage { protected test() { AccessPage = PageWebType.WX; } protected s ...