Esempio n. 1
0
        /// <summary>
        /// 开始下载
        /// </summary>
        /// <param name="url">下载url</param>
        /// <param name="fileName">保存文件名</param>
        public void download(string url, string fileName)
        {
            if (mCurDownloadSta == eDownloadSta.STA_ING)
            {
                Console.WriteLine("url:{0} is downloading...", url);
                return;
            }

            if (mHttpUrl != url)//新的下载文件要重新计数
            {
                init();
            }
            else
            {
                FullSize          = 0.0;
                DownloadedSize    = 0.0;
                LengthInOneSecond = 0.0;
                RemainTime        = 0;
            }

            mHttpUrl      = url;
            mSaveFileName = fileName;
            if (fileName.Length < 1)
            {
                mSaveFileName = Directory.GetCurrentDirectory() + Path.GetFileName(url);
            }
            mCurDownloadSta = eDownloadSta.STA_START;
            //Task.Run(() =>
            //{

            //});
            mTimer.Start();
            mCurDownloadSta = eDownloadSta.STA_ING;
            Console.WriteLine("start download:");

            int ret = -1;

            try
            {
                ret = dowLoadFile();
            }
            catch (Exception e)
            {
                ret = -100;
                Console.WriteLine("dowload err, err:" + e.Message);
                ErrorHappend?.Invoke(this, new UnhandledExceptionEventArgs(e, false));
            }
            mCurDownloadSta = eDownloadSta.STA_FINISH;
            mTimer.Stop();

            if (ret < 0)
            {
                Progress?.Invoke(this, new DownloadProgressEventArgs(FullSize, FullSize, 0, 0, eDownloadSta.STA_ERR));
            }
            else if (ret == 0)
            {
                Progress?.Invoke(this, new DownloadProgressEventArgs(FullSize, FullSize, 0, 0, eDownloadSta.STA_FINISH));
            }
            else
            {
                Progress?.Invoke(this, new DownloadProgressEventArgs(DownloadedSize, Speed, RemainTime, TotalTime, eDownloadSta.STA_FINISH));
            }
        }
Esempio n. 2
0
        /// <summary>
        /// 下载文件(同步)  支持断点续传
        /// </summary>
        public int dowLoadFile()
        {
            int errCnt = 0;

            //打开上次下载的文件或新建文件
            long       startPos = 0;
            FileStream fs       = null;

            if (File.Exists(mSaveFileName))//文件已经存在就继续下载
            {
                try
                {
                    fs = File.OpenWrite(mSaveFileName);
                    if (null == fs)
                    {
                        Console.WriteLine("open file failed:" + mSaveFileName);
                        return(-1);
                    }
                    startPos = fs.Length;
                }
                catch (Exception e)
                {
                    Console.WriteLine("open file err:" + e.Message);
                    ErrorHappend?.Invoke(this, new UnhandledExceptionEventArgs(e, false));
                    if (null != fs)
                    {
                        fs.Close();
                        return(-2);
                    }
                }
            }
            else//新文件
            {
                fs = new FileStream(mSaveFileName, FileMode.Create);
                Console.WriteLine("创建文件");
                startPos = 0;
            }

            /**获取文件大小**/
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(mHttpUrl);

            if (null == request)
            {
                return(-3);
            }

            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36";
            //request.KeepAlive = true;//保持连接
            //设置Range值,请求指定位置开始的数据,实现断点续传
            request.AddRange(startPos);//request.AddRange(startPos, endPos)获取指定范围数据,续传跟重传(中间某部分)可使用该函数

            WebResponse respone = null;

            //注:断点续传必须在request后、并设置AddRange后第一次获取的Response才是正确的数据流
            try
            {
                respone = request.GetResponse();
                if (null == respone)
                {
                    request.Abort();
                    fs.Close();
                    return(-4);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("getResponse err:" + e.Message);
                ErrorHappend?.Invoke(this, new UnhandledExceptionEventArgs(e, false));
                fs.Close();
                return(-4);
            }

            FullSize = Convert.ToDouble(respone.ContentLength) + startPos;
            //发送文件大小
            if (FullSize < 0)
            {
                Console.WriteLine("获取文件大小失败");
                return(-5);
            }

            //文件错误,清空文件
            if (FullSize < startPos)
            {
                fs.SetLength(0);//截断文件,相当于是清空文件内容
                Console.WriteLine("文件错误,清空后重新下载");
            }

            DownloadedSize = startPos;

            //文件已下载
            if (DownloadedSize >= FullSize)
            {
                fs.Close();
                respone.Close();
                request.Abort();
                //Finished?.Invoke(this, new EventArgs());
                Console.WriteLine("文件已经下载");
                return(0);
            }

            fs.Seek(startPos, SeekOrigin.Begin);   //移动文件流中的当前指针
            //Console.WriteLine("startPos:{0}", startPos);
            Stream responseStream = null;

            byte[] dataBuf = new byte[BUF_SIZE];

            //打开网络连接
            try
            {
                //向服务器请求,获得服务器回应数据流
                responseStream = respone.GetResponseStream();
                if (null == responseStream)
                {
                    fs.Close();
                    respone.Close();
                    request.Abort();
                    return(-6);
                }

                int nReadSize = 0;

                do
                {
                    //读取数据
                    nReadSize = responseStream.Read(dataBuf, 0, BUF_SIZE);
                    if (nReadSize > 0)
                    {
                        fs.Write(dataBuf, 0, nReadSize);
                        //此处应该判断是否写入成功

                        //已下载大小
                        DownloadedSize += nReadSize;

                        LengthInOneSecond += nReadSize;
                    }
                    else
                    {
                        errCnt++;
                        if (errCnt > READ_ERR_MAX_CNT)
                        {
                            Console.WriteLine("下载出错,退出下载");
                            break;
                        }
                    }

                    if (mCurDownloadSta == eDownloadSta.STA_STOP)
                    {
                        Console.WriteLine("停止下载");
                        break;
                    }
                } while (DownloadedSize < FullSize);

                responseStream.Close();
                respone.Close();
                fs.Close();
                request.Abort();

                //Console.WriteLine("DownloadedSize:{0}, FullSize:{1}", DownloadedSize, FullSize);
                if (DownloadedSize == FullSize)//下载完成
                {
                    Console.WriteLine("下载完成");
                    //Finished?.Invoke(this, new EventArgs());

                    return(100);
                }
                return(1);
            }
            catch (Exception ex)//下载失败
            {
                responseStream.Close();
                respone.Close();
                fs.Close();
                request.Abort();
                Console.WriteLine("下载失败:" + ex.ToString());
                return(-7);
            }
        }