C#实现文件断点续传下载的方法

本文实例讲述了C#实现文件断点续传下载的方法。分享给大家供大家参考。具体实现方法如下:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.IO;
using System.Text;
using System.Net;
namespace simpleDemo
{
 class Program
 {
  /// <summary>
  /// 下载文件保留字
  /// </summary>
  public static string PERSIST_EXP = ".cdel";
  /// <summary>
  public static void Main(string[] args)
  {
   string path = "D:\\aa.txt";
   string ec = getFileEncoding(path, "GB2312");
   print("coding: " + ec);
   // string content = fileReader(path, Encoding.GetEncoding(ec));
   // print(content);
   //fileWriter(path, "测试内容11", Encoding.GetEncoding(ec));
   string url = "http://www.XXX.com/20120920172200024.flv";
   string path1 = "D:\\aa1.flv";

   download(url, path1);
   //gapDownload(url, path1);
   //t(url);
  }
  public static void t(string url) {
   HttpWebRequest request = (System.Net.HttpWebRequest)HttpWebRequest.Create(url);

   //WebResponse response = httpClient.CreateGetHttpResponse(url, 3000, null, null);
   try {
    WebResponse response = request.GetResponse();
    WebHeaderCollection headers = response.Headers;
    print(response.ContentLength);
    request = (System.Net.HttpWebRequest)HttpWebRequest.Create(url);
    request.AddRange(11); //设置Range值
    WebResponse response1 = request.GetResponse();
    print(response1.ContentLength);

    foreach (string key in headers)
    {
     print(key + "----- " + headers.Get(key));
    }
    string disposition = headers.Get("Content-Disposition");
    print(disposition);
   }catch(Exception e){
    print(e.Message);
   }
   //string fileName = disposition.Substring(disposition.IndexOf("\""));
   //print(fileName);
  }
  public static void download(string url, string path) {
   if (File.Exists(path))
   {
    print("文件己存在!是否重新下载?");
    return;
   }
   else {
    path = path + PERSIST_EXP;
    simpleDownload(url,path);//开始下载
   }
  }
  /// <summary>
  /// 下载网络资源(支持断点续传)
  /// </summary>
  /// <param name="url"></param>
  /// <param name="path"></param>
  public static void simpleDownload(string url, string path)
  {
   HttpWebRequest request = httpClient.getWebRequest(url, 0);
   WebResponse response = null;
   FileStream writer = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
   long lStartPos = writer.Length; ;//当前文件大小
   long currentLength = 0;
   long totalLength = 0;//总大小
   if (File.Exists(path))//断点续传
   {
    response = request.GetResponse();
    long sTotal = response.ContentLength;
    if (sTotal == lStartPos) {
     close(writer);
     File.Move(path, path.Replace(PERSIST_EXP, ""));
     print("下载完成!");
     return;
    }
    request = httpClient.getWebRequest(url, (int)lStartPos);
    //设置Range值
    writer.Seek(lStartPos, SeekOrigin.Begin);//指针跳转
    response = request.GetResponse();
    totalLength = response.ContentLength + lStartPos; //总长度
    currentLength = lStartPos; //当前长度
   }
   else
   {
    response = request.GetResponse();
    totalLength = response.ContentLength;
   }
   Stream reader = response.GetResponseStream();
   byte[] buff = new byte[1024];
   int c = 0; //实际读取的字节数
   while ((c = reader.Read(buff, 0, buff.Length)) > 0)
   {
    currentLength += c;
    writer.Write(buff, 0, c);
    progressBar(currentLength, totalLength);//进度条
    writer.Flush();
   }
   close(writer);
   if (currentLength == totalLength)
   {
    File.Move(path, path.Replace(PERSIST_EXP, ""));
    print("下载完成!");
   }

   if (reader != null)
   {
    reader.Close();
    reader.Dispose();
    response.Close();
   }
  }
  private static void close(FileStream writer)
  {
   if (writer != null)
   {
    writer.Close();
    writer.Dispose();
   }
  }
  /// <summary>
  /// 进度条
  /// </summary>
  /// <param name="currentLength">当前长度</param>
  /// <param name="totalLength">总长度</param>
  public static void progressBar(Object currentLength, Object totalLength)
  {
   double aaa = System.Convert.ToDouble(currentLength);
   double bbb = System.Convert.ToDouble(totalLength);
   print(currentLength + "/" + totalLength + "__" + (aaa / bbb).ToString("0.00 %"));
  }
  /// <summary>
  /// 系统输出
  /// </summary>
  /// <param name="obj"></param>
  public static void print(Object obj){
   Console.WriteLine(obj);
  }
  public static void printStr(string[] str)
  {
   foreach (string d in str)
   {
    print(d);
   }
  }
  /// <summary>
  /// 文件写
  /// </summary>
  /// <param name="path">文件路径</param>
  /// <param name="content">要写入的内容</param>
  public static void fileWriter(string path,string content,Encoding encoding)
  {
   if (File.Exists(path))
   {
    StreamWriter sw = new StreamWriter(path, true, encoding);
    sw.WriteLine(content);
    sw.Flush();
    sw.Close();
   }
  }
  /// <summary>
  /// 读文件,返回内容
  /// </summary>
  /// <param name="path">文件路径</param>
  /// <param name="enCoding">默认编码格式</param>
  /// <returns></returns>
  public static string fileReader(string path,Encoding enCoding) {
   StringBuilder sb = new StringBuilder();
   if(enCoding == null){
    enCoding = Encoding.Default;
   }
   //读取文件
   StreamReader sr = new StreamReader(path, enCoding);
    string s = "";
    while ((s = sr.ReadLine()) != null)
    {
     sb.AppendLine(s);
    }
    if(sr != null)
     sr.Close();
   return sb.ToString();
  }
  /// <summary>
  /// 获取文件编码格式
  /// </summary>
  /// <param name="path">文件路径</param>
  /// <param name="defaultEncoding">默认编码</param>
  /// <returns></returns>
  public static string getFileEncoding(string path, string defaultEncoding) {
   string ed = defaultEncoding;
   if (File.Exists(path)) {
    FileStream fs = new FileStream(path, FileMode.Open);
    ed = GetEncoding(fs, defaultEncoding);
    if (fs != null)
     fs.Close();
   }
   return ed;
  }
  /// <summary>
  /// 取得一个文本文件流的编码方式。
  /// </summary>
  /// <param name="stream">文本文件流。</param>
  /// <param name="defaultEncoding">默认编码方式。当该方法无法从文件的头部取得有效的前导符时,将返回该编码方式。</param>
  /// <returns></returns>
  public static string GetEncoding(FileStream stream, string defaultEncoding)
  {
   string targetEncoding = defaultEncoding;
   if (stream != null && stream.Length >= 2)
   {
    //保存文件流的前4个字节
    byte byte1 = 0;
    byte byte2 = 0;
    byte byte3 = 0;
    byte byte4 = 0;
    //保存当前Seek位置
    long origPos = stream.Seek(0, SeekOrigin.Begin);
    stream.Seek(0, SeekOrigin.Begin);
    int nByte = stream.ReadByte();
    byte1 = Convert.ToByte(nByte);
    byte2 = Convert.ToByte(stream.ReadByte());
    if (stream.Length >= 3)
    {
     byte3 = Convert.ToByte(stream.ReadByte());
    }
    if (stream.Length >= 4)
    {
     byte4 = Convert.ToByte(stream.ReadByte());
    }
    //根据文件流的前4个字节判断Encoding
    //Unicode {0xFF, 0xFE};
    //BE-Unicode {0xFE, 0xFF};
    //UTF8 = {0xEF, 0xBB, 0xBF};
    if (byte1 == 0xFE && byte2 == 0xFF)//UnicodeBe
    {
     targetEncoding = Encoding.BigEndianUnicode.BodyName;
    }
    if (byte1 == 0xFF && byte2 == 0xFE && byte3 != 0xFF)//Unicode
    {
     targetEncoding = Encoding.Unicode.BodyName;
    }
    if (byte1 == 0xEF && byte2 == 0xBB && byte3 == 0xBF)//UTF8
    {
     targetEncoding = Encoding.UTF8.BodyName;
    }
    //恢复Seek位置
    stream.Seek(origPos, SeekOrigin.Begin);
   }
   return targetEncoding;
  }
 }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.IO;
namespace simpleDemo
{
 /// <summary>
 /// 公用 Http 请求类
 /// </summary>
 class httpClient
 {
  /// <summary>
  /// 获取基础WebRequest
  /// </summary>
  /// <param name="url">请求地址</param>
  /// <param name="lStartPos">请求的开始位置</param>
  /// <returns></returns>
  public static HttpWebRequest getWebRequest(string url, int lStartPos)
  {
   HttpWebRequest request = null;
   try
   {
    request = (System.Net.HttpWebRequest)HttpWebRequest.Create(url);
    request.AddRange(lStartPos); //设置Range值
   }
   catch (Exception ex)
   {
    Program.print(ex.Message);
   }
   return request;
  }
 }
}

希望本文所述对大家的C#程序设计有所帮助。

(0)

相关推荐

  • asp.net(C#)中上传大文件的几中常见应用方法

    几种常见的方法,本文主要内容包括: 第一部分:首先我们来说一下如何解决ASP.net中的文件上传大小限制的问题,我们知道在默认情况下ASP.NET的文件上传大小限制为2M,一般情况下,我们可以采用更改Web.Config文件来自定义最大文件大小,如下: 这样上传文件的最大值就变成了4M,但这样并不能让我们无限的扩大 MaxRequestLength的值,因为ASP.NET会将全部文件载入内存后,再加以处理.解决的方法是利用隐含的 HttpWorkerRequest,用它的GetPreloaded

  • asp.net(c#)开发中的文件上传组件uploadify的使用方法(带进度条)

    在Web开发中,有很多可以上传的组件模块,利用HTML的File控件的上传也是一种办法,不过这种方式,需要处理的细节比较多,而且只能支持单文件的操作.在目前Web开发中用的比较多的,可能uploadify(参考http://www.uploadify.com/)也算一个吧,不过这个版本一直在变化,他们的脚本调用也有很大的不同,甚至调用及参数都一直在变化,很早的时候,那个Flash的按钮文字还没法变化,本篇随笔主要根据项目实际,介绍一下3.1版本的uploadify的控件使用,这版本目前还是最新的

  • C# 通用文件上传类

    1.Upfile.aspx: 复制代码 代码如下: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Upfile.aspx.cs" Inherits="Inc_Upfile" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http

  • C# 文件上传 默认最大为4M的解决方法

    1,环境:window 2003 ,IIS6.0 要首先要修改IIS6.0中的asp请求的最大字节数,默认时为200K: 方法:打开位于 C:\Windows\System32\Inetsrv 中的 metabase.XML, 并修改 AspMaxRequestEntityAllowed 为你需要的值(例如 "1073741824", 1GB): 技术背景: 在 IIS 6.0 中, AspMaxRequestEntityAllowed 属性指定了一个 ASP 请求(Request)可

  • C#实现HTTP下载文件的方法

    本文实例讲述了C#实现HTTP下载文件的方法.分享给大家供大家参考. 主要实现代码如下: 复制代码 代码如下: /// <summary> /// Http下载文件 /// </summary> public static string HttpDownloadFile(string url, string path) {     // 设置参数     HttpWebRequest request = WebRequest.Create(url) as HttpWebReques

  • C#实现Web文件上传的两种方法实例代码

    1. C#实现Web文件的上传 使用C#如何实现文件上传的功能呢?下面笔者简要介绍一下. 首先,在你的Visual C# web project 中增加一个上传用的Web Form,为了要上传文件,需要在ToolBox中选择HTML类的File Field控件,将此控件加入到Web Form中,然而此时该控件还不是服务端控件,我们需要为它加上如下一段代码:<input id=PreviousFile1 type=file size=49 runat="server">,这样

  • C#中使用HttpDownLoadHelper下载文件实例

    本文实例讲述了C#使用HttpDownLoadHelper下载文件的方法.分享给大家供大家参考.具体实现方法如下: 复制代码 代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; using System.Threading; namespace ProjectWenDangManage.Framework {     /// <sum

  • C#实现HTTP上传文件的方法

    本文实例讲述了C#实现HTTP上传文件的方法.分享给大家供大家参考.具体实现方法如下: 发送文件代码如下: 复制代码 代码如下: /// <summary> /// Http上传文件 /// </summary> public static string HttpUploadFile(string url, string path) {     // 设置参数     HttpWebRequest request = WebRequest.Create(url) as HttpWe

  • C# Winform下载文件并显示进度条的实现代码

    方法一: 效果如下图所示: 代码如下: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WinShowDown { public partial class F

  • C#实现文件上传及文件下载功能实例代码

    废话不多说了,直接给大家贴代码了,具体代码如下所示: public ActionResult Upload() { // var pathUrl = "http://" + Request.Url.Authority; var file = Request.Files["Filedata"]; var uploadFileName = file.FileName; string filePath = "/File/" + uploadFileNa

随机推荐