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. MySQL存储过程中实现回滚

    用存储过程处理复杂的业务时,可能涉及到对多张表格的操作,在任一个步骤出了问题,就需要对前面的操作回滚.举例实现: DROP PROCEDURE IF EXISTS pro_test; CREATE P ...

  2. 【转】工控老鬼】西门子S7200入门&精通【1】S7200硬件大全

    转载地址:http://blog.sina.com.cn/s/blog_669692a601016i5f.html     工控老鬼提醒以下的信息和资料可能不全或者不准确,如有疑问可以查阅西门子中国网 ...

  3. HTML5 History 模式

    vue-router 默认 hash 模式 -- 使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载. 如果不想要很丑的 hash,我们可以用路由的 his ...

  4. hdu5737(2016多校联赛第2场D)

    题意:给2组数据a和b数组,每次有2种操作:(+,l,r,x)把a数组第l个到第r个元素全置为x,(?,l,r)查询[l,r]之间哪些位置满足a[i]>=b[i](i>=l &&a ...

  5. sublime SublimeTmpl 添加vue模板

    sublime2安装时候报错在control中加下面的代码 重新启动,可以进行安装 import urllib2,os; pf='Package Control.sublime-package'; i ...

  6. jQuery学习笔记(五)jQuery中的表单

    目录 单行文本框的应用 表单验证 上次我们说完jQuery中的动画之后,我们再来看一种jQuery在Web网页应用最为广泛的一种形式,这就是jQuery对表单的操作,通过jQuery对表单的操作,可以 ...

  7. WebForm简单控件,复合控件

    简单控件: 1.Label 会被编译成span标签 属性: Text:文本内容 CssClass:CSS样式 Enlabled:是否可用 Visible:是否可见 __________________ ...

  8. 随机生成验证码import random

    #!/usr/bin/env python import random temp = "" for i in range(6) : num = random.randrange(0 ...

  9. 游戏对象消失三种方法的区别?(enabled/Destroy/active)

    gameObject.renderer.enabled=fasle是控制一个物体是否在屏幕上渲染或显示  而物体实际还是存在的 只是想当于隐身 而物体本身的碰撞体还依然存在的GameObject.De ...

  10. 。linux桌面与命令行

    1.输入用户名和密码登录到系统2.vi /etc/inittab3.修改id:后对应的值为5(桌面模式),id:后对应的值改成3(命令行模式)先用命令#startx启动到桌面模式,然后 Ctrl + ...