下载-断点续传

     /// <summary>
        ///  断点续传
        /// </summary>
        /// <param name="savePath">保存路径</param>
        /// <param name="loadPath">下载路径</param>
        /// <param name="fileName">文件名称</param>
        /// <param name="flag">备份区分,默认备份名,原文件+.back</param>
        /// <returns></returns>
        public static bool ResumeDownloadFile(string savePath, string loadPath, string fileName = null, bool flag = true)
        {
            // 自定义文件名为空的情况
            if (string.IsNullOrEmpty(fileName))
            {
                // 取得下载文件名
                fileName = Path.GetFileName(loadPath);
            }
            savePath = savePath + fileName;
            // 判断保存路径是否存在,备份原文件
            JustFileAndDic(savePath, true);
            // 定义临时下载路径
            string strLocalPathTemp = savePath + PersistExp;
            // 文件下载结果.
            bool bDownload = true;

            //打开上次下载的文件或新建文件 
            long lStartPos = 0;
            FileStream fs;
            if (File.Exists(strLocalPathTemp))
            {
                fs = File.OpenWrite(strLocalPathTemp);
                lStartPos = fs.Length;
                fs.Seek(lStartPos, SeekOrigin.Current); //移动文件流中的当前指针 
            }
            else
            {
                fs = new FileStream(strLocalPathTemp, FileMode.Create);
                lStartPos = 0;
            }

            //打开网络连接 
            try
            {
                // 定义验证证书的回调函数.
                ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loadPath);
                if (lStartPos > 0)
                    request.AddRange((int)lStartPos); //设置Range值

                //向服务器请求,获得服务器回应数据流 
                Stream ns = request.GetResponse().GetResponseStream();

                byte[] nbytes = new byte[512];
                int nReadSize = 0;
                nReadSize = ns.Read(nbytes, 0, 512);
                while (nReadSize > 0)
                {
                    fs.Write(nbytes, 0, nReadSize);
                    nReadSize = ns.Read(nbytes, 0, 512);
                }
                fs.Close();
                ns.Close();
                // 将文件复制到指定文件夹
                File.Copy(strLocalPathTemp, savePath);
                // 删除临时文件
                File.Delete(strLocalPathTemp);
            }
            catch (Exception e)
            {
                fs.Close();
                // 设定下载结果为false.
                bDownload = false;
            }

            // 返回下载结果.
            return bDownload;
        }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章