0

ファイルをアップロードおよびダウンロードするための C# アプリケーションを作成しています。ダウンロードは WebClient オブジェクトとそのDownloadAsycDownloadメソッドを使用します。ダウンロードは、複数のファイルに対して正常に機能します。必要なだけファイルをダウンロードします。

私の問題は、フォームに動的に追加されるさまざまな進行状況バーにすべてのファイルの進行状況を表示できないことですflowlayout control

これが私のコードです:

public ProgressBar[] bar;
public int countBar=0;

...

    bar[countBar] = new ProgressBar();
    flowLayoutPanel1.Controls.Add(bar[countBar]);
    countBar++;

    request.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownoadInProgress);
    request.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCompleted);
    request.DownloadFileAsync(new Uri(this.uri), localPath);

    byte[] fileData = request.DownloadData(this.uri);
    FileStream file = File.Create(localPath);
    file.Write(fileData, 0, fileData.Length);
    file.Close();
}

public void DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
    flowLayoutPanel1.Controls.Remove(bar[countBar]);
    countBar--;
    MessageBox.Show("Download Completed");
}

public void DownoadInProgress(object sender, DownloadProgressChangedEventArgs e)
{
    bar[countBar].Maximum = total_bytes;
    bar[countBar].Value = (int)e.BytesReceived;                
}
4

2 に答える 2

1

進行状況バーにインデックスを付けるためにカウントを使用していますが、1 つが完了すると、ファイルに関連付けられているものを実際に削除する必要がある最後のものを削除します。

この場合、 a Dictionary<WebClient, ProgressBar>(may not be WebCliet- should be the type senderin the events) を使用することをお勧めします。

...
var progBar = new ProgressBar();
progBar.Maximum = 100;
flowLayoutPanel1.Controls.Add(progBar);

request.DownloadProgressChanged += DownoadInProgress;
request.DownloadFileCompleted += DownloadFileCompleted;
request.DownloadFileAsync(new Uri(this.uri), localPath);

dic.Add(request, progBar);

// You shouldn't download the file synchronously as well!
// You're already downloading it asynchronously.

// byte[] fileData = request.DownloadData(this.uri);
// FileStream file = File.Create(localPath);
// file.Write(fileData, 0, fileData.Length);
// file.Close();

countBar次に、完全に削除して、新しいメソッドを使用できます。

public void DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
    // Can remove (WebClient) cast, if dictionary is <object, ProgressBar>
    var request = (WebClient)sender;
    flowLayoutPanel1.Controls.Remove(dic[request]);
    dic.Remove(request);
    MessageBox.Show("Download Completed");
}

public void DownoadInProgress(object sender, DownloadProgressChangedEventArgs e)
{
    var progBar = dic[(WebClient)sender];
    progBar.Value = e.ProgressPercentage;                
}
于 2013-05-01T07:07:25.523 に答える