Beispiel #1
0
        /// <summary>
        /// 下载指定路径的文件
        /// </summary>
        /// <param name="downloadItem">下载任务信息</param>
        /// <returns>下载结果</returns>
        public PageRequestResults FileDownload(DownloadMusicTask downloadTask)
        {
            if (!string.IsNullOrEmpty(downloadTask.DownloadUrl))
            {
                // 设置请求信息,使用GET方式获得数据
                HttpWebRequest musicFileReq = (HttpWebRequest)WebRequest.Create(downloadTask.DownloadUrl);
                musicFileReq.AllowAutoRedirect = true;
                musicFileReq.Method = "GET";
                //设置超时时间
                musicFileReq.Timeout = SearchConfig.TIME_OUT;
                //获取代理
                IWebProxy proxy = SearchConfig.GetConfiguredWebProxy();
                //判断代理是否有效
                if (proxy != null)
                {
                    //代理有效时设置代理
                    musicFileReq.Proxy = proxy;
                }

                // 判断是否断点续传()
                FileStream downloadStream,configStream;
                if (!File.Exists(downloadTask.MusicSavePath))
                {
                    //不是断点续传时,创建下载文件和配置文件
                    downloadStream = new FileStream(downloadTask.MusicSavePath, FileMode.Create, FileAccess.Write);
                    //configStream = new FileStream(downloadTask.MusicConfigPath, FileMode.Create, FileAccess.Write);
                    downloadTask.DownloadSize = 0;
                }
                else
                {
                    //断点续传时读入文件,并且从已下载的位置开始下载
                    downloadStream = System.IO.File.OpenWrite(downloadTask.MusicSavePath);
                    downloadTask.DownloadSize = downloadStream.Length;
                    downloadStream.Seek(downloadTask.DownloadSize, SeekOrigin.Current); //移动文件流中的当前指针
                    musicFileReq.AddRange((int)downloadTask.DownloadSize);  //设置请求头的Range值
                }

                try
                {
                    // 获取HTTP请求响应
                    using (HttpWebResponse musicFileRes = (HttpWebResponse)musicFileReq.GetResponse())
                    {
                        // 如果HTTP返回200--正常,返回206表示是断点续传
                        //
                        if (musicFileRes.StatusCode == HttpStatusCode.OK
                            || musicFileRes.StatusCode == HttpStatusCode.PartialContent
                            || musicFileRes.StatusCode == HttpStatusCode.Moved
                            || musicFileRes.StatusCode == HttpStatusCode.MovedPermanently)
                        {
                            // 获取响应的页面流
                            using (Stream remoteStream = musicFileRes.GetResponseStream())
                            {
                                using (downloadStream)
                                {
                                    //设置下载状态和下载大小,状态为准备下载,并汇报进度
                                    downloadTask.DownloadStatus = DownloadStatus.ST_READY_DOWNLOAD;

                                    //此处要加上已下载的大小,因为断线续传时返回的ContentLength是从Range出到结束的大小
                                    downloadTask.FileSize = musicFileRes.ContentLength + downloadTask.DownloadSize;
                                    downloadManager.ReportProgress(downloadTask);  //汇报当前下载进度

                                    //用户统计速度
                                    TimeSpan totalTimeSpan = TimeSpan.Zero;
                                    int totalTimeSize = 0;

                                    //开始下载数据,检查是否下载完成
                                    while (downloadTask.DownloadSize < downloadTask.FileSize)
                                    {
                                        // 检查是否被取消
                                        if (downloadManager.TaskCanCancle(downloadTask.DownloadTaskID))
                                        {
                                            //如果任务被取消退出
                                            downloadTask.DownloadStatus = DownloadStatus.ST_CANCEL_DOWNLOAD;
                                            break;
                                        }

                                        // 检查是否被暂停
                                        if (downloadManager.TaskCanStop(downloadTask.DownloadTaskID))
                                        {
                                            //汇报暂停时下载进度
                                            downloadTask.DownloadStatus = DownloadStatus.ST_STOP_DOWNLOAD;
                                            downloadManager.ReportProgress(downloadTask);
                                            break;
                                        }

                                        // 正常下载,从流中读取到文件流中
                                        byte[] buffer = new byte[1024];
                                        TimeSpan readStart = new TimeSpan(DateTime.Now.Ticks);
                                        int readSize = remoteStream.Read(buffer, 0, buffer.Length);
                                        TimeSpan readEnd = new TimeSpan(DateTime.Now.Ticks);
                                        TimeSpan ts = readEnd.Subtract(readStart).Duration();
                                        totalTimeSpan += ts;
                                        totalTimeSize += readSize;

                                        //写入文件
                                        downloadStream.Write(buffer, 0, readSize);
                                        downloadTask.DownloadSize += readSize;

                                        //计算速度,400ms刷新一次
                                        if (totalTimeSpan.Milliseconds > 400)
                                        {
                                            downloadTask.DownloadSpeed = (totalTimeSize / totalTimeSpan.Milliseconds) * 1000;
                                            totalTimeSpan = TimeSpan.Zero;
                                            totalTimeSize = 0;
                                        }

                                        //汇报当前下载进度
                                        downloadTask.DownloadStatus = DownloadStatus.ST_IS_DOWNLOAD;
                                        downloadManager.ReportProgress(downloadTask);
                                    }

                                    // 如果完成,设置状态
                                    if (downloadTask.DownloadSize == downloadTask.FileSize)
                                    {
                                        downloadTask.DownloadStatus = DownloadStatus.ST_OVER_DOWNLOAD;
                                    }
                                    //完成下载,程序退出
                                    return PageRequestResults.Success;
                                }
                            }
                        }
                        else
                        {
                            //汇报下载进度
                            downloadTask.DownloadStatus = DownloadStatus.ST_ERROR_DOWNLOAD;
                            downloadManager.ReportProgress(downloadTask);
                            return PageRequestResults.UnknowException;
                        }
                    }
                }
                catch (WebException webEx)
                {
                    //出错时汇报下载进度和错误信息
                    downloadTask.Error = webEx;
                    downloadTask.DownloadStatus = DownloadStatus.ST_ERROR_DOWNLOAD;
                    downloadManager.ReportProgress(downloadTask);

                    // 异常时返回异常的原因
                    if (webEx.Status == WebExceptionStatus.Timeout)
                    {
                        return PageRequestResults.TimeOut;
                    }
                    else if (webEx.Status == WebExceptionStatus.SendFailure)
                    {
                        return PageRequestResults.SendFailure;
                    }
                    else if (webEx.Status == WebExceptionStatus.ConnectFailure)
                    {
                        return PageRequestResults.ConnectFailure;
                    }
                    else if (webEx.Status == WebExceptionStatus.ReceiveFailure)
                    {
                        return PageRequestResults.ReceiveFailure;
                    }
                    else if (webEx.Status == WebExceptionStatus.NameResolutionFailure)
                    {
                        return PageRequestResults.DNSFailure;
                    }
                    else if (webEx.Status == WebExceptionStatus.RequestProhibitedByProxy)
                    {
                        return PageRequestResults.ProxyFailure;
                    }
                    else
                    {
                        return PageRequestResults.UnknowException;
                    }
                }
                catch (Exception ex)
                {
                    //出错时汇报下载进度和错误信息
                    downloadTask.Error = ex;
                    downloadTask.DownloadStatus = DownloadStatus.ST_ERROR_DOWNLOAD;
                    downloadManager.ReportProgress(downloadTask);
                    return PageRequestResults.UnknowException;
                }
                finally
                {
                    downloadStream.Close();
                    //configStream.Close();
                }
            }
            return PageRequestResults.UrlIsNull;
        }
        /// <summary>
        /// 开始下载
        /// </summary>
        /// <param name="argument">要下载的音乐信息</param>
        public void RunWorkerAsync(DownloadMusicTask downloadItem)
        {
            //如果目前下载数量小于5条,则通过委托启动新的下载任务

            //设置下载状态
            downloadItem.IsStop = false;
            downloadItem.DownloadStatus = DownloadStatus.ST_READY_DOWNLOAD;

            // 对于新增的任务,添加到同步管理表
            if (!asyncOperationtTable.ContainsKey(downloadItem.DownloadTaskID))
            {
                AsyncOperation asyncOperation = AsyncOperationManager.CreateOperation(downloadItem.DownloadTaskID);
                lock (asyncOperationLock)
                {
                    asyncOperationtTable.Add(downloadItem.DownloadTaskID, asyncOperation);
                }
            }

            if (downloadTable.Count < 5)
            {
                // 如果开始的是等待任务,则从等待列表删除
                if (waitDownloadTable.ContainsKey(downloadItem.DownloadTaskID))
                {
                    lock (waitTableLock)
                    {
                        waitDownloadTable.Remove(downloadItem.DownloadTaskID);
                    }
                }

                //加入到下载列表
                lock (downloadTableLock)
                {
                    downloadTable.Add(downloadItem.DownloadTaskID, downloadItem);
                }

                //新启一个线程开始下载
                this.threadStart.BeginInvoke(downloadItem, null, null);
            }
            else  //如果目前下载数量大于5则进入等待下载队列
            {
                //设置下载状态
                downloadItem.IsStop = true;
                downloadItem.DownloadStatus = DownloadStatus.ST_WAIT_DOWNLOAD;

                //添加到等待列表
                lock (waitTableLock)
                {
                    waitDownloadTable.Add(downloadItem.DownloadTaskID, downloadItem);
                }

                ReportProgress(downloadItem); //报道下载进度
            }
        }
Beispiel #3
0
        /// <summary>
        /// 提交下载歌曲任务
        /// </summary>
        private void btnDownload_Click(object sender, EventArgs e)
        {
            if (searchSelectIndex != -1)
            {
                //设置下载任务
                DownloadMusicTask task = new DownloadMusicTask();
                task.DownloadUrl = dataGridView1["MusicUrl", searchSelectIndex].Value.ToString();
                task.MusicName = dataGridView1["MusicName", searchSelectIndex].Value.ToString();
                task.MusicSavePath = FileManager.GetSavaPath(task.MusicName, dataGridView1["MusicFormat", searchSelectIndex].Value.ToString());
                if (string.IsNullOrEmpty(task.MusicSavePath))
                {
                    task = null;
                    MessageBox.Show("无法保存文件");
                }
                task.DownloadTaskID = Guid.NewGuid();

                //添加到下载列表
                DataRow row = downListTable.NewRow();
                row["name"] = task.MusicName;
                row["size"] = string.Empty;
                row["status"] = string.Empty;
                row["process"] = 0;
                row["speed"] = string.Empty;
                row["link"] = task.DownloadUrl;
                row["GUID"] = task.DownloadTaskID;
                row["task"] = task;
                downListTable.Rows.Add(row);

                //开始下载
                downloadManager.RunWorkerAsync(task);
            }
        }