private void GetCurrentFileList() { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strCurrentCDN); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { string html = reader.ReadToEnd(); Regex regex = new Regex("<a href=\".*\\.rar\">(?<name>.*)</a>"); MatchCollection matches = regex.Matches(html); if (matches.Count > 0) { foreach (Match match in matches) { if (match.Success) { URLToDownload thisFile = new URLToDownload { URL = strCurrentCDN + match.Groups["name"].ToString(), File = this.strBasePath + @"\@DayZ\" + match.Groups["name"].ToString() }; downloadList.Enqueue(thisFile); } } } } } }
private void DownloadNextFile() { if (downloadList.Count > 0) { URLToDownload nextFile = downloadList.Dequeue(); UpdateIfNeeded(nextFile); } else { LaunchDayZ(); } }
private void UnRarFile(URLToDownload args) { //Extract the file to the AddOns folder using (Stream stream = File.OpenRead(args.File)) { UpdateStatus("Extracting " + args.File); var reader = ReaderFactory.Open(stream); while (reader.MoveToNextEntry()) { if (!reader.Entry.IsDirectory) { Console.WriteLine(reader.Entry.FilePath); reader.WriteEntryToDirectory(this.strBasePath + @"\@DayZ\Addons", ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite); } } } //Delete the rar File.Delete(args.File); }
private void DownloadFile(URLToDownload args) { UpdateStatus("Скачиваю " + args.FileName + " ... (" + ++DwnCountCurrent + " из " + DwnCountTotal + ")"); DwnFile = ArmaPaths["mod"] + "\\" + args.FileName; DwnPath = args.Path; SetPBarState(true); WebClient webClient = new WebClient(); webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DwnProgressChanged); webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(DwnCompleted); try { if (File.Exists(ArmaPaths["mod"] + "\\" + args.FileName)) // Удаление недокаченного файла, если имеется. { File.Delete(ArmaPaths["mod"] + "\\" + args.FileName); } webClient.DownloadFileAsync(new Uri(UpdatesURL + args.FileName), ArmaPaths["mod"] + "\\" + args.FileName); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
//Download update file only if needed private bool UpdateIfNeeded(URLToDownload getFile, string strType = "modified") { //Get our stored eTag for this URL string strETag = ""; strETag = GetEtag(getFile.URL); UpdateStatus("Checking " + getFile.URL); try { //Set up a request and include our eTag HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(getFile.URL); request.Method = "GET"; if (strETag != "") { if (strType == "etag") { request.Headers[HttpRequestHeader.IfNoneMatch] = strETag; } else { try { strETag = strETag.Replace("UTC", "GMT"); //Fix for weird servers not sending correct formate datetime request.IfModifiedSince = Convert.ToDateTime(strETag); } catch (Exception e) { MessageBox.Show("Unable to set modified date for URL: " + getFile.URL + "; " + e.Message); } } } //Grab the response, will throw an exception if it's a 304 (not modified) HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //We need to check if an elevation is required if (this.strBasePath.IndexOf("Program Files") > 0) Elevate(); //Download the file bgDownloadWorker.RunWorkerAsync(getFile); response.Close(); //Save the etag if (strType == "etag") { if (response.Headers[HttpResponseHeader.ETag] != null) SaveEtag(getFile.URL, response.Headers[HttpResponseHeader.ETag]); } else { if (response.Headers[HttpResponseHeader.LastModified] != null) SaveEtag(getFile.URL, response.Headers[HttpResponseHeader.LastModified]); } return true; } catch (System.Net.WebException ex) { if (ex.Response != null) { using (HttpWebResponse response = ex.Response as HttpWebResponse) { if (response.StatusCode == HttpStatusCode.NotModified) { //304 means there is no update available UpdateStatus(getFile.URL + " is up to date"); DownloadNextFile(); return false; } else { // Wasn't a 200, and wasn't a 304 so let the log know MessageBox.Show(string.Format("Failed to check " + getFile.URL + ". Error Code: {0}")); return false; } } } else return false; } catch (Exception e) { MessageBox.Show(string.Format("Failed to update " + getFile.URL + ". Error: {0}", e.Message)); return false; } }
//Download update file only if needed private bool UpdateIfNeeded(URLToDownload getFile, string strType = "modified") { //Get our stored eTag for this URL string strETag = ""; strETag = GetEtag(getFile.URL); UpdateStatus("Checking " + getFile.URL); try { //Set up a request and include our eTag HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(getFile.URL); request.Method = "GET"; if (strETag != "") { if (strType == "etag") { request.Headers[HttpRequestHeader.IfNoneMatch] = strETag; } else { try { strETag = strETag.Replace("UTC", "GMT"); //Fix for weird servers not sending correct formate datetime request.IfModifiedSince = Convert.ToDateTime(strETag); } catch (Exception e) { MessageBox.Show("Unable to set modified date for URL: " + getFile.URL + "; " + e.Message); } } } //Grab the response, will throw an exception if it's a 304 (not modified) HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //We need to check if an elevation is required if (this.strBasePath.IndexOf("Program Files") > 0) { Elevate(); } //Download the file bgDownloadWorker.RunWorkerAsync(getFile); response.Close(); //Save the etag if (strType == "etag") { if (response.Headers[HttpResponseHeader.ETag] != null) { SaveEtag(getFile.URL, response.Headers[HttpResponseHeader.ETag]); } } else { if (response.Headers[HttpResponseHeader.LastModified] != null) { SaveEtag(getFile.URL, response.Headers[HttpResponseHeader.LastModified]); } } return(true); } catch (System.Net.WebException ex) { if (ex.Response != null) { using (HttpWebResponse response = ex.Response as HttpWebResponse) { if (response.StatusCode == HttpStatusCode.NotModified) { //304 means there is no update available UpdateStatus(getFile.URL + " is up to date"); DownloadNextFile(); return(false); } else { // Wasn't a 200, and wasn't a 304 so let the log know MessageBox.Show(string.Format("Failed to check " + getFile.URL + ". Error Code: {0}")); return(false); } } } else { return(false); } } catch (Exception e) { MessageBox.Show(string.Format("Failed to update " + getFile.URL + ". Error: {0}", e.Message)); return(false); } }
// Worker thread to grab the file private void DownloadFile(object sender, DoWorkEventArgs e) { URLToDownload args = e.Argument as URLToDownload; // the URL to download the file from string sUrlToReadFileFrom = args.URL; // the path to write the file to string sFilePathToWriteFileTo = args.File; // first, we need to get the exact size (in bytes) of the file we are downloading Uri url = new Uri(sUrlToReadFileFrom); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); response.Close(); // gets the size of the file in bytes Int64 iSize = response.ContentLength; // keeps track of the total bytes downloaded so we can update the progress bar Int64 iRunningByteTotal = 0; // use the webclient object to download the file using (System.Net.WebClient client = new System.Net.WebClient()) { UpdateStatus("Downloading " + sUrlToReadFileFrom); // open the file at the remote URL for reading using (System.IO.Stream streamRemote = client.OpenRead(new Uri(sUrlToReadFileFrom))) { // using the FileStream object, we can write the downloaded bytes to the file system using (Stream streamLocal = new FileStream(sFilePathToWriteFileTo, FileMode.Create, FileAccess.Write, FileShare.None)) { // loop the stream and get the file into the byte buffer int iByteSize = 0; byte[] byteBuffer = new byte[iSize]; while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0) { // write the bytes to the file system at the file path specified streamLocal.Write(byteBuffer, 0, iByteSize); iRunningByteTotal += iByteSize; // calculate the progress out of a base "100" double dIndex = (double)(iRunningByteTotal); double dTotal = (double)byteBuffer.Length; double dProgressPercentage = (dIndex / dTotal); int iProgressPercentage = (int)(dProgressPercentage * 100); // update the progress bar bgDownloadWorker.ReportProgress(iProgressPercentage); } // clean up the file stream streamLocal.Close(); } // close the connection to the remote server streamRemote.Close(); } //Extract and delete the file UnRarFile(args); } }