WebClient多文件下载错误
本文关键字:错误 文件下载 WebClient | 更新日期: 2023-09-27 18:10:39
我使用以下代码从我的web服务器下载50多个文件
private void button5_Click(object sender, EventArgs e)
{
WebClient client = new WebClient();
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
//downloads
client.DownloadFileAsync(new Uri("http://www.site.com/file/loc.file"), @"c:'app'loc ");
client.DownloadFileAsync(new Uri("http://www.site.com/file/loc.file"), @"c:'app'loc ");
client.DownloadFileAsync(new Uri("http://www.site.com/file/loc.file"), @"c:'app'loc ");
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = bytesIn / totalBytes * 100;
progressBar.Value = int.Parse(Math.Truncate(percentage).ToString());
}
private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("Game Update Finished!");
}
我想下载一个文件在一个持续的进度条,我得到了大部分的编码完成,但当我点击"下载"按钮,我得到以下错误
WebClient不支持并发I/O操作
我需要做什么?
感受不同:
- 它可以以并行方式下载多个文件(每一个流)一个文件)。
- 但是不能使用多个流下载一个文件。
下面是一个例子(主窗口包含一个"开始"按钮和五个进度条):
public partial class MainWindow : Window
{
private WebClient _webClient;
private ProgressBar[] _progressBars;
private int _index = 0;
public MainWindow()
{
InitializeComponent();
_progressBars = new [] {progressBar1, progressBar2, progressBar3, progressBar4, progressBar5};
ServicePointManager.DefaultConnectionLimit = 5;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Interlocked.Increment(ref _index);
if (_index > _progressBars.Length)
return;
_webClient = new WebClient();
_webClient.DownloadProgressChanged += WebClient_DownloadProgressChanged;
_webClient.DownloadFileCompleted += WebClient_DownloadFileCompleted;
_webClient.DownloadFileAsync(new Uri("http://download.thinkbroadband.com/5MB.zip"),
System.IO.Path.GetTempFileName(),
_index);
}
private void WebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs args)
{
var index = (int) args.UserState;
_progressBars[index-1].Value = args.ProgressPercentage;
}
private void WebClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs args)
{
var index = (int)args.UserState;
MessageBox.Show(args.Error == null
? string.Format("Download #{0} completed!", index)
: string.Format("Download #{0} error!'n'n{1}", index, args.Error));
}
}
您正在使用同一个WebClient
实例并行运行多个下载-错误告诉您这是不支持的-您要么:
- 使用多个
WebClient
实例(每次并行下载一个)或 - 一个接一个下载
相关信息:
- http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx
- http://msdn.microsoft.com/en-us/magazine/cc700359.aspx
WebClient不支持每个实例并发I/O操作(多个下载),因此您需要为每个下载创建一个单独的WebClient实例。您仍然可以异步执行每个下载,并使用相同的事件处理程序。