private void GetFileFromServer(object state) { try { Abc abc = state as Abc; var request = (HttpWebRequest)WebRequest.Create(Url); request.AddRange(abc.From, abc.To); using (var response = request.GetResponse()) using (var stream = response.GetResponseStream()) using (var output = File.Create(abc.Path)) { stream.CopyTo(output); progressBar.Minimum = 0; double receive = (double)output.Length; Percentage = receive / FileSize * 100; Interlocked.Add(ref location, (int)Percentage); Invoke(new Action(() => { lblStatus.Text = $"Downloaded {string.Format("{0}%", location)}"; progressBar.Value = int.Parse(Math.Truncate((double)location).ToString()); progressBar.Update(); s++; })); } if (s == inputFilePaths.Length) { CombineMultipleFilesIntoSingleFile(); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void btnStart_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txtAddress.Text) && !string.IsNullOrWhiteSpace(txtAddress.Text) && !string.IsNullOrEmpty(txtThreadCount.Text) && !string.IsNullOrWhiteSpace(txtThreadCount.Text) && !string.IsNullOrEmpty(txtFileName.Text) && !string.IsNullOrWhiteSpace(txtFileName.Text) && !string.IsNullOrEmpty(txtFileFormat.Text) && !string.IsNullOrWhiteSpace(txtFileFormat.Text)) { try { Url = txtAddress.Text; FileName = txtFileName.Text; Path = txtPath.Text + '/' + FileName + '.' + txtFileFormat.Text; int count = int.Parse(txtThreadCount.Text); inputFilePaths = new string[count]; var webRequest = HttpWebRequest.Create(Url); webRequest.Method = "HEAD"; int fileSizeInByte; using (var webResponse = webRequest.GetResponse()) { var fileSize = webResponse.Headers.Get("Content-Length"); FileSize = fileSizeInByte = Convert.ToInt32(fileSize); } int packetSize = fileSizeInByte / (count - 1); for (int i = 0; count > 0; i += packetSize) { inputFilePaths[inputFilePaths.Length - count] = FileName + (inputFilePaths.Length - count); Abc abc = new Abc(i, i + packetSize - 1, FileName + (inputFilePaths.Length - count)); if (count == 1) { abc.To = fileSizeInByte; } WaitCallback workItem = new WaitCallback(GetFileFromServer); ThreadPool.QueueUserWorkItem(workItem, abc); count--; } } catch (ArgumentNullException ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (ArgumentException ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show("Укажите необходимые данные", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }