public DownloadProgressEventArgs(double curSize, double speed, uint remainTime, uint spanTime, eDownloadSta sta) { CurrentSize = curSize; Speed = speed; RemainTime = remainTime; SpanTime = spanTime; State = sta; }
string mHttpUrl = ""; //http下载路径 //务必使用此函数初始化,因为定时器需要再主类创建 public HttpHelper(System.Timers.Timer _timer) { if (mTimer == null) { mTimer = _timer; mTimer.Interval = TIMER_TICK; mTimer.Stop(); mTimer.Elapsed += new System.Timers.ElapsedEventHandler(tickEventHandler); //到达时间的时候执行事件; mTimer.AutoReset = true; //设置重复执行(true); mTimer.Enabled = true; //设置执行tickEventHandler事件 } init(); mCurDownloadSta = eDownloadSta.STA_FINISH; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return(true); // **** Always accept }; }
/// <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)); } }
//停止下载 public void downloadStop() { mCurDownloadSta = eDownloadSta.STA_STOP; mTimer.Stop(); }