C#斷點續傳的實現


斷點續傳的實現方式有很多,下面介紹個依賴本地以下載的文件大小來實現斷點續傳

        public static void HttpDownloadEx(string url,
            string path,
            bool overwrite,
            Action<string, HttpWebResponse> doneCallback = null,
            Action<string, string, long, long> downloadingCallback = null) 
        {

            // 設置參數
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            //發送請求並獲取相應回應數據
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

            string contentType = response.Headers["Content-Type"];

            //斷點續傳
            FileStream fStream = null;
            long sPosition = 0;
            Stream responseStream = null;

            try
            {
                long totalLength = response.ContentLength;
                if (System.IO.File.Exists(path))
                {
                    fStream = System.IO.File.OpenWrite(path);
                    sPosition = fStream.Length;
                    if (sPosition == totalLength)
                    {
                        doneCallback?.Invoke(path, response); //文件是完整的,直接結束下載任務
                        return;
                    }
                    fStream.Seek(sPosition, SeekOrigin.Current);
                }
                else
                {
                    fStream = new FileStream(path, FileMode.Create);
                    sPosition = 0;
                }

                HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                if (sPosition > 0)
                {
                    myRequest.AddRange(sPosition);             //設置Range值
                }

                //向服務器請求,獲得服務器的回應數據流
                responseStream = myRequest.GetResponse().GetResponseStream();

                //定義一個字節數據
                byte[] btContent = new byte[512];
                int intSize = 0;
                intSize = responseStream.Read(btContent, 0, 512);
                while (intSize > 0)
                {
                    fStream.Write(btContent, 0, intSize);
                    intSize = responseStream.Read(btContent, 0, 512);
                    downloadingCallback?.Invoke(path, contentType, totalLength, fStream.Length);
                }
            }
            catch
            {//(Exception ex)
                throw;
            }
            finally
            {
                //關閉流
                if (responseStream != null)
                {
                    responseStream.Close();
                    responseStream.Dispose();
                }
                if (fStream != null)
                {
                    fStream.Close();
                    fStream.Dispose();
                }
            }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM