2017-01-07 2 views
2

코드가 작동 중입니다. 그러나 이제는 각 파일의 다운로드 진행률을 progressBar1에 표시하고 있습니다. 하지만 디자이너 (이미 추가됨)에 전체 다운로드 진행 상태를 표시하려면 progressBar2을 추가하고 싶습니다. 어떻게 계산하여 progressBar2에 표시 할 수 있습니까?전체 다운로드를 표시하는 새로운 progressBar를 어떻게 추가 할 수 있습니까?

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.IO; 
using System.Net; 
using System.Threading; 
using System.Diagnostics; 

namespace DownloadFiles 
{ 
    public partial class Form1 : Form 
    { 
     Stopwatch sw = new Stopwatch();  
     int count = 0; 
     PictureBoxBigSize pbbs; 
     ExtractImages ei = new ExtractImages(); 

     public Form1() 
     { 
      InitializeComponent(); 

     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 

     } 

     private void btnDownload_Click(object sender, EventArgs e) 
     { 
      downloadFile(filesUrls); 
     } 

     private Queue<string> _downloadUrls = new Queue<string>(); 

     private async void downloadFile(IEnumerable<string> urls) 
     { 
      foreach (var url in urls) 
      { 
       _downloadUrls.Enqueue(url); 
      } 

      await DownloadFile(); 
     } 

     private async Task DownloadFile() 
     { 
      if (_downloadUrls.Any()) 
      { 
       WebClient client = new WebClient(); 
       client.DownloadProgressChanged += ProgressChanged; 
       client.DownloadFileCompleted += Completed; 

       var url = _downloadUrls.Dequeue(); 

       await client.DownloadFileTaskAsync(new Uri(url), @"C:\Temp\DownloadFiles\" + count + ".jpg"); 
       return; 
      } 
     } 

     private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e) 
     { 
      // Calculate download speed and output it to labelSpeed. 
      Label2.Text = string.Format("{0} kb/s", (e.BytesReceived/1024d/sw.Elapsed.TotalSeconds).ToString("0.00")); 

      // Update the progressbar percentage only when the value is not the same. 
      double bytesIn = double.Parse(e.BytesReceived.ToString()); 
      double totalBytes = double.Parse(e.TotalBytesToReceive.ToString()); 
      double percentage = bytesIn/totalBytes * 100; 
      ProgressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());//e.ProgressPercentage; 
      // Show the percentage on our label. 
      Label4.Text = e.ProgressPercentage.ToString() + "%"; 

      // Update the label with how much data have been downloaded so far and the total size of the file we are currently downloading 
      Label5.Text = string.Format("{0} MB's/{1} MB's", 
       (e.BytesReceived/1024d/1024d).ToString("0.00"), 
       (e.TotalBytesToReceive/1024d/1024d).ToString("0.00")); 
     } 

     // The event that will trigger when the WebClient is completed 
     private async void Completed(object sender, AsyncCompletedEventArgs e) 
     { 
      if (e.Cancelled == true) 
      { 
       MessageBox.Show("Download has been canceled."); 
      } 
      else 
      { 
       ProgressBar1.Value = 100; 
       count++; 
       await DownloadFile(); 
      } 
     } 
    } 
} 
+0

다운로드 할 때마다 다운로드 한 총 바이트 수를 저장하는 int를 만듭니다 (int bytesCompleted). 별도의 방법으로 다운로드하려는 모든 파일을 반복하여 해당 번호를 별도의 int (int totalBytesAllDownloads)에 저장합니다. progressChanged에서 ProgressBar2 ((e.BytesReceived + bytesCompleted)/totalBytesDownloaded)로 다시보고하십시오. 나는 그것이 그것보다 더 이상 복잡해야한다고 생각하지 않는다! –

+0

@Shn_Android_Dev 코드로 수행하는 방법을 보여 주시겠습니까? 나는 분리 된 방법과 나머지를 이해하지 못했다. 죄송합니다. –

답변

0

봅니다 (당신이 결정하는 어떤 기존의 방법 또는 수정) 다운로드 할 필요 바이트의 총량을 계산이 방법을 추가 : 그래서 내가 여기했던하는 것은 추가

long totalBytesToDownload = 0; 
List<FileInfo> files; 
private void getTotalBytes(IEnumerable<string> urls) 
{ 
    files = new List<FileInfo>(urls.Count()); 
    foreach(string url in urls) 
    { 
     files.Add(new FileInfo(url)); 
    } 
    files.ForEach(file => totalBytesToDownload += file.Length); 
} 

을 다운로드 할 총 바이트 수를 가져 오는 메소드 및 다운로드하려는 각 파일의 파일 크기를 저장하는 변수를 작성하는 메소드입니다.이 파일은 여기에서 1 분 안에 사용됩니다.

먼저 Complete 이벤트에서 각 파일 다운로드 후 바이트 수를 저장하는 변수를 만들어야합니다.이 변수는 나중에 사용합니다.

long bytesFromCompletedFiles = 0; 
private async void Completed(object sender, AsyncCompletedEventArgs e) 
{ 
    if (e.Cancelled == true) 
    { 
     MessageBox.Show("Download has been canceled."); 
    } 
    else 
    { 
     ProgressBar1.Value = 100; 
     count++; 
     bytesFromCompletedFiles += files[count - 1].Length; 
     await DownloadFile(); 
    } 
} 

그리고 마지막으로, 우리는 당신의 ProgressBar2를 완료 ProgressChanged 이벤트를 업데이트 할 수 있습니다

private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e) 
{ 
    // Calculate download speed and output it to labelSpeed. 
    Label2.Text = string.Format("{0} kb/s", (e.BytesReceived/1024d/sw.Elapsed.TotalSeconds).ToString("0.00")); 

    // Update the progressbar percentage only when the value is not the same. 
    double bytesInCurrentDownload = double.Parse(e.BytesReceived.ToString()); 
    double totalBytesCurrentDownload = double.Parse(e.TotalBytesToReceive.ToString()); 
    double percentageCurrentDownload = bytesInCurrentDownload/totalBytesCurrentDownload * 100; 
    ProgressBar1.Value = int.Parse(Math.Truncate(percentageCurrentDownload).ToString());//e.ProgressPercentage; 
                     // Show the percentage on our label. 
    Label4.Text = e.ProgressPercentage.ToString() + "%"; 

    // Update the label with how much data have been downloaded so far and the total size of the file we are currently downloading 
    Label5.Text = string.Format("{0} MB's/{1} MB's", 
     (e.BytesReceived/1024d/1024d).ToString("0.00"), 
     (e.TotalBytesToReceive/1024d/1024d).ToString("0.00")); 

    //Let's update ProgressBar2 
    double totalBytesDownloaded = e.BytesReceived + bytesFromCompletedFiles; 
    double percentageTotalDownload = totalBytesDownloaded/totalBytesToDownload * 100; 
    ProgressBar2.Value = int.Parse(Math.Truncate(percentageTotalDownload)).ToString(); 
} 

희망이 당신을 위해 작동합니다!

+0

줄에서 예외가 발생합니다. ProgressBar2.Value = int.Parse (Math.Truncate (percentageTotalDownload)). ToString(); 처음에는 오류가 일부에 있던이 라인에 오류가 발생했습니다 : Math.Truncate은 (percentageTotalDownload 오류는 다음과 같습니다 심각도 \t 코드 \t 설명 \t 프로젝트 \t 파일 \t 라인 \t 억제 상태 오류 \t 인수 1 \t CS1503 : 더블 '에서 변환 할 수 없습니다 'to'string ' –

+0

그런 다음 줄에서 ToString()을 다음 줄로 변경하려고 시도했습니다. progressBar2.Value = int.Parse (Math.Truncate (percentageTotalDownload) .ToString()); 오류가 발생하지만 프로그램을 실행할 때이 줄에 예외가 발생했습니다 예외 : Message = 입력 문자열이 올바른 형식이 아닙니다. 그래서 오류 및 progressBar2.Value 문제를 해결하는 방법을 잘 모르겠습니다. 라인. –

+0

그냥 넣어보십시오 ProgressBar2.Value = percen tageTotalDownload. ProgressBar2.Value는 double을 찾고 있지만 답변의 코드 서식이 ProgessBar1 형식을 기반으로 지정되었습니다. –

관련 문제