C#Web客户端正在下载多个文件
本文关键字:文件 下载 客户端 C#Web | 更新日期: 2023-09-27 18:29:41
我还有一个问题:(.
我正在尝试为我的应用程序下载多个文件。
我的问题是:我该怎么做才能检查第一次下载是否完成,然后继续第二次下载,以此类推?
这是我的代码atm:
private void DownloadBukkit()
{
MySingleton.Instance.FirstStartProgress = "Downloading Bukkit.jar... Please stand by...";
webClient.DownloadFileAsync(new Uri(MySingleton.Instance.BukkitDownloadLink), Jar_Location);
webClient.DownloadProgressChanged += backgroundWorker1_ProgressChanged;
webClient.DownloadFileCompleted += (webClient_DownloadFileCompleted);
}
private void DownloadDll()
{
if (!webClient.IsBusy)
{
MySingleton.Instance.FirstStartProgress = "Downloading HtmlAgilityPack.dll... Please stand by...";
webClient2.DownloadFileAsync(new Uri(Dll_HtmlAgilityPackUrl), Dll_HtmlAgilityPackLocation);
webClient2.DownloadProgressChanged += backgroundWorker1_ProgressChanged;
webClient2.DownloadFileCompleted += (webClient2_DownloadFileCompleted);
}
}
void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
DownloadDll();
}
void webClient2_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
Invoke((MethodInvoker)
Close);
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Invoke((MethodInvoker)
delegate
{
labelProgress.Text = MySingleton.Instance.FirstStartProgress;
progressBar1.Value = e.ProgressPercentage;
});
}
我已经检查了这个链接:使用webclient下载FileAsync多个文件,但我真的不知道如何植入:(.(我对C#很陌生)
DownloadFileCompleted事件是通知您已完成文件下载的信号。
来自MSDN:
每次异步文件下载操作时都会引发此事件完成。
从您的代码中还不清楚webClient和webClient2在哪里以及如何声明,但本质上,您可以在第一个DownloadFileCompleted事件触发时开始第二次下载。但是,请注意,如果使用WebClient
的两个独立实例,则可以同时执行两个不同文件的下载。
以下是您可以根据需要更改的快速代码。
WebClient client = null;
public FileDownloader()
{
InitializeComponent();
client = new WebClient();
client.DownloadProgressChanged += client_DownloadProgressChanged;
client.DownloadFileCompleted += client_DownloadFileCompleted;
}
void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
lblMessage.Text = "File Download Compeleted.";
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
lblMessage.Text = e.ProgressPercentage + " % Downloaded.";
}
private void StartDownload(object sender, RoutedEventArgs e)
{
if (client == null)
client = new WebClient();
//Loop thru your files for eg. file1.dll, file2.dll .......etc.
for (int index = 0; index < 10; index++)
{
//loop on files
client.DownloadFileAsync(
new Uri(
@"http://mywebsite.com/Files/File" + index.ToString() + ".dll"
, UriKind.RelativeOrAbsolute),
@"C:'Temp'file+" + index.ToString() + ".dll");
}
}