我有另一个问题:(。
我正在尝试为我的应用程序下载多个文件。
我的问题是:如何检查第一次下载是否已完成,然后继续第二次下载等等,我该怎么办?
这是我的代码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;
});
}
我已经检查了这个链接:DownloadFileAsync multiple files using webclient但我真的不明白如何植入这个:(。(我对C#很新)
答案 0 :(得分:3)
DownloadFileCompleted事件是您知道您已完成下载文件的信号。
来自MSDN:
每次异步文件下载操作时都会引发此事件 的完成强>
从您的代码中可以看出,webClient和webClient2的声明位置和方式并不清楚,但实质上,您可以在触发第一个DownloadFileCompleted事件时开始第二次下载。但请注意,如果您使用WebClient
的2个单独实例,则可以同时执行2个不同文件的下载。
答案 1 :(得分:0)
以下是您可以根据自己的要求更改的快进代码。
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");
}
}