private static void Download(SongItem item) { try { Directory.CreateDirectory(Config.SongsCachePath); } catch (Exception) { } dlItem = item; dlItem.setStatus(SongItem.SongStatus.Downloading); if (item.Module.HandleDownlaod) // 如果搜索模块负责下载文件 { Center.Mainw.setDownloadStatus("由搜索模块负责下载中"); switch (item.Module.SafeDownload(item)) { case 1: // 下载成功 dlItem.setStatus(SongItem.SongStatus.WaitingPlay); Center.Logg("歌曲下载 下载成功:" + item._SongName); Center.Mainw.setDownloadStatus("搜索模块返回下载成功"); return; case 0: // 下载失败 错误信息由module输出 default: Center.RemoveSong(item); Center.Mainw.setDownloadStatus("搜索模块返回下载失败"); return; } } else // 如果搜索模块不负责下载文件 { wc = new WebClient(); wc.DownloadProgressChanged += onDownloadProgressChanged; wc.DownloadFileCompleted += onDownloadFileCompleted; wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.450 Safari/537.35"); try { sw.Reset(); lastUpdateDownloadedSize = 0; lastUpdateTime = DateTime.Now; wc.DownloadFileAsync(new Uri(item._DownloadURL), item._FilePath); Center.Mainw.setDownloadStatus("正在连接服务器"); sw.Start(); DownloadWatchDog.Start(); downloadFlag = true; // 正在下载歌曲 } catch (Exception ex) { sw.Reset(); Center.Logg("下载歌曲" + item._SongName + "出错:" + ex.Message, true, true); Center.Mainw.setDownloadStatus("下载失败:" + ex.Message); } while (downloadFlag) { Thread.Sleep(500); } dlItem = null; } }
private static void onDownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { bool sucFlag = true; if (e.Cancelled) { Center.Logg("下载被取消"); Center.Mainw.setDownloadStatus("下载被取消"); sucFlag = false; try { File.Delete(dlItem.FilePath); } catch (Exception) { } } else if (e.Error != null) { Center.Logg("下载出错 " + e.Error.Message, true, true); Center.Mainw.setDownloadStatus("下载出错 " + e.Error.Message); sucFlag = false; } if (sucFlag) { Center.Logg("歌曲下载 下载成功:" + dlItem._SongName, false, true); Center.Mainw.setDownloadStatus("下载完毕"); dlItem.setStatus(SongItem.SongStatus.WaitingPlay); } else { Center.RemoveSong(dlItem); } DownloadWatchDog.Stop(); wc = null; downloadFlag = false; // 允许进行下一首歌的下载 }