如何逐个下载多个文件。使用我的代码。
//Download File
public void DownloadFile(string url, string folderfile)
{
WebClient wc = new WebClient();
try
{
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadCompleted);
wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadChanged);
wc.DownloadFileAsync(new Uri(url), folderfile);
}
catch (Exception ex)
{
MessageBox.Show("Error: \n\n" + ex.Message);
}
}
private void DownloadChanged(object sender, DownloadProgressChangedEventArgs e)
{
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = bytesIn / totalBytes * 100.0;
int percente = int.Parse(Math.Truncate(percentage).ToString());
PBar.Value = percente;
progress.Text = percente + " %";
size.Text = string.Format("{0} MB / {1} MB", (e.BytesReceived / 1024d / 1024d).ToString("0.00"), (e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00"));
}
private void DownloadCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show("Erro: " + e.Error.Message);
}
else
{
info.Text = "Download Success.";
}
}
public void CheckFileDownload()
{
string urlGame = "http://localhost/";
string Game = "Game.exe";
string Support = "Support.Xml";
string Info = "Info.xml";
if (!File.Exists(Game))
{
//Download Game
DownloadFile(urlGame + Game, Game);
info.Text = "Downloading: " + Game;
//If the game is downloading full
DownloadFile(urlGame + Info, Info);
DownloadFile(urlGame + Support, Support);
info.Text = "Updating information...";
}
}
private void Launcher_Load(object sender, EventArgs e)
{
CheckFileDownload();
}
因为我需要在下载游戏后更新检查点文件。
我看了几个主题,但没有成功。 感谢所有帮助我的人...抱歉我的英语不好
谢谢所有帮助我的人。我将非常感激......
答案 0 :(得分:0)
如果性能不是问题,您可以使用DownloadFile,然后它将按您指定的顺序下载它们,您不需要为所有重叠的异步操作而烦恼。由于您只下载了3个文件,因此异步编码的时间节省可能不值得。
或者,您可以为要下载的每个文件(在类级别,而不是在任何函数内)定义标记,这些文本可以在Dictionary中,也可以只包含3个bool变量。在DownloadFilAsync documentation中注意userToken参数,用于标识3个文件中的哪个文件已完成下载。用它来设置完成的标志;然后在上次下载完成后,继续进行下一步发生的事情。