在C#中下载多个文件(一次只能下载一个/队列)
本文关键字:下载 一个 队列 一次 文件 | 更新日期: 2023-09-27 18:21:59
我正在用C#编写一个更新程序,现在我需要一些帮助(我是这门语言的新手,请解释你的提示:D)
我的代码:
System.IO.Directory.CreateDirectory("tmp");
int mmx = updnec.Count();
label6.Text = "0/" + mmx;
MessageBox.Show(label6.Text);
int mmn = 0;
foreach (string lz in link)
{
MessageBox.Show(lz);
client.DownloadFileAsync(new Uri(lz), "tmp/update00" + mmn + ".exe");
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
label6.Text = mmn + "/" + mmx;
mmn = +1;
//Whithout that while{} - part, it tries to download all links from the list at once. But I don't want the program to do that. I don't want it to show a message all the time, too, but when i leave that while{} - part empty, the program just freezes and doesn't even download.
while (progressBar1.Maximum != progressBar1.Value)
{
MessageBox.Show("Test");
}
}
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar1.Maximum = (int)e.TotalBytesToReceive;
progressBar1.Value = (int)e.BytesReceived;
string sysload = progressBar1.Value /1000000 + "/" + progressBar1.Maximum /1000000 + " MB geladen";
label12.Text = sysload;
}
请阅读我代码中的注释。
如何解决我的问题!?请帮帮我!
Reditec
编辑:
label11.Text = System.DateTime.Now.ToString();
backgroundWorker1.RunWorkerAsync(link);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
List<string> lz = (List<string>)e.Argument;
int mmn = 0;
progressBar1.Style = ProgressBarStyle.Blocks;
System.IO.Directory.CreateDirectory("tmp");
int mmx = 10;
label6.Text = "0/" + mmx;
foreach (string lkz in lz)
using (var client = new WebClient())
{
MessageBox.Show("Hallo" + lkz);
client.DownloadFile(lkz, "tmp/update00" + mmn + ".exe");
}
}
尝试使用BackgroundWorker并同步下载文件,而不是异步下载。你可以在这里找到一个例子:http://www.codeproject.com/Tips/83317/BackgroundWorker-and-ProgressBar-demo
这里有一个例子:
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var links = new[] { "link1", "link2" };
var percentProgressStep = (100 / links.Length) + 1
using (var client = new WebClient())
foreach (string l in links)
{
client.DownloadFile(l, Path.GetTempFileName());
backgroundWorker1.ReportProgress(percentProgressStep);
}
}