程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> HTTP協議斷點續傳,協議斷點續傳

HTTP協議斷點續傳,協議斷點續傳

編輯:C#入門知識

HTTP協議斷點續傳,協議斷點續傳


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace HttpDemo
{
    class Program
    {
        //需要下載的路徑
        static string url = "http://www.aseoe.com/demo/api/jquery_aseoe_001.zip";
        //獲取文件全稱
        static string fileName = Path.GetFileName(url);
        //保存路徑
        static string localPath = "D:\\HttpCeShi\\" + fileName;
        //未下載完後面加.temp後綴名
        static string tempPath = localPath + ".temp";
        //偏移量(斷點)
        static int pos;

        static void Main(string[] args)
        {
            DownLoad();
            Console.ReadLine();
        }
        public static void DownLoad()
        {
            //如果存在要更新的文件就結束
            if (File.Exists(localPath))
                return;

            Stream localfs = null;
            //如果不存在未上傳完文件(需斷點續傳文件)
            if (File.Exists(tempPath))
            {
                localfs = new FileStream(tempPath, FileMode.Open);
            }

            else
            {
                localfs = new FileStream(tempPath, FileMode.Create);
            }
            //獲取斷點
            pos = (int)localfs.Length;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Headers.Add("Accept-Charset", "GBK,utf-8");
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
            request.Method = "GET";
            request.Timeout = 30000;
            //文件總長度單位(B)
            long total = request.GetResponse().ContentLength;
            Console.WriteLine("總長度為:" + total);
            if (pos > 0)
                request.AddRange(pos);//偏移到斷點

            HttpWebResponse responseResult = (HttpWebResponse)request.GetResponse();
            using (Stream stream = responseResult.GetResponseStream())
            {
                byte[] buffer = new byte[total - pos];

                int readSize = stream.Read(buffer, 0, buffer.Length);
                while (readSize > 0)
                {
                    localfs.Write(buffer, 0, readSize);
                    readSize = stream.Read(buffer, 0, buffer.Length);
                    Console.WriteLine("已下載:" + localfs.Length);
                }
                localfs.Close();
                File.Move(tempPath, localPath);//將臨時文件改為正常文件後綴
                Console.WriteLine("下載完成!!!");
            }

        }


    }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved