我正在使用 BackgroundDownloader 从 URL 下载文件。我必须在进度条中显示每个下载百分比(如 1%、2%、3%、...)并显示为文本。但是每次下载(只有一个文件)我都会得到一堆下载百分比(比如 40%、60% ......)。这是我的代码:
private async void btnDownload_Click(object sender, RoutedEventArgs e)
{
Uri source;
StorageFile destinationFile;
StorageFolder folder;
string destination = "SampleImage.png";
if (!Uri.TryCreate(txtUrl.Text.Trim(), UriKind.Absolute, out source))
{
txtUrl.Text = "Pls provide correct URL...";
return;
}
try
{
folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("SampleFolder", CreationCollisionOption.OpenIfExists);
destinationFile = await folder.CreateFileAsync(destination, CreationCollisionOption.GenerateUniqueName);
}
catch
{
txtProgress.Text = "Opss something went wrong... try again....";
return;
}
BackgroundDownloader downloader = new BackgroundDownloader();
DownloadOperation download = downloader.CreateDownload(source, destinationFile);
if (download != null)
{
try
{
var progress = new Progress<DownloadOperation>(ProgressCallback); // for showing progress
await download.StartAsync().AsTask(cancelProcess.Token, progress);
}
catch (TaskCanceledException)
{
txtProgress.Text = "Canceled";
}
catch(Exception)
{
txtProgress.Text = "Something went wrong pls try again....";
}
}
}
//for showing progress
private void ProgressCallback(DownloadOperation obj)
{
double progress = 0;
if (obj.Progress.BytesReceived > 0)
{
progress = obj.Progress.BytesReceived * 100 / obj.Progress.TotalBytesToReceive;
if (progress > 0)
{
txtProgress.Text = string.Format("Downloading your file.... {0}%", progress);
pbDownloading.Value = progress; // passing progress bar value
}
}
else
{
txtProgress.Text = "Check your internet connection...";
}
}
我怎样才能获得下载的每一个进度百分比......?或任何其他最好的方法来做到这一点......?