private void BeforeFileDownload(UpdateFile file) { //Create any parent directories for this file var dir = Path.GetDirectoryName(file.Path); if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) { Directory.CreateDirectory(dir); } }
private void AddToUpdateList(UpdateFile file, List <UpdateFile> downloadFirst) { if (IsUpdaterFile(file.Path.ToLower())) { downloadFirst.Add(file); } else { mDownloadQueue.Push(file); } }
private void CheckFileData(UpdateFile file, byte[] fileData) { if (fileData.Length != file.Size) { throw new Exception("[File Length Mismatch - Got " + fileData.Length + " bytes, Expected " + file.Size + "]"); } //Check MD5 var md5Hash = ""; using (var md5 = MD5.Create()) { using (var stream = new MemoryStream(fileData)) { md5Hash = BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLowerInvariant(); } } if (md5Hash != file.Hash) { throw new Exception("File Hash Mismatch"); } }
private void BeforeReplaceFile(UpdateFile file) { //Delete .old first if exists if (File.Exists(file.Path + ".old")) { try { File.Delete(file.Path + ".old"); } catch { } } //Delete Existing File if (File.Exists(file.Path)) { try { File.Delete(file.Path); } catch { try { File.Move(file.Path, file.Path + ".old"); } catch { throw new Exception("Failed to delete or move existing file!"); } } } if (file.Path == Path.GetFileName(Assembly.GetEntryAssembly().Location)) { ReplacedSelf = true; } }
private async void DownloadUpdates() { while (mDownloadQueue.Count > 0 && !mFailed) { UpdateFile file = null; var streamDl = false; lock (mUpdate) { if (mDownloadQueue.TryPop(out file)) { mActiveDownloads.TryAdd(file, 0); } } if (file != null) { //Download File BeforeFileDownload(file); try { //Use WebClient to Download File To Memory var wc = new WebClient(); wc.DownloadProgressChanged += ((sender, args) => mActiveDownloads[file] = args.BytesReceived); var rawUri = mBaseUrl + "/" + Uri.EscapeUriString(file.Path) + "?token=" + Environment.TickCount; var fileUri = new Uri(rawUri); var fileData = await wc.DownloadDataTaskAsync(fileUri); wc.Dispose(); CheckFileData(file, fileData); BeforeReplaceFile(file); //Save New File File.WriteAllBytes(file.Path, fileData); lock (mUpdate) { mCompletedDownloads.Add(file); mActiveDownloads.TryRemove(file, out long val); mDownloadedBytes += file.Size; if (IsUpdaterFile(file.Path)) { mUpdaterContentLoaded = true; } } } catch (Exception ex) { lock (mUpdate) { mActiveDownloads.TryRemove(file, out long val); if (mFailedDownloads.ContainsKey(file)) { mFailedDownloads[file]++; } else { mFailedDownloads.TryAdd(file, 1); } if (mFailedDownloads[file] > 2) { Exception = new Exception("[" + file.Path + "] - " + ex.Message, ex); mFailed = true; } else { mDownloadQueue.Push(file); } } } } Thread.Sleep(10); } }