URLからファイルをダウンロードするためにBackgroundDownloaderを使用しています。各ダウンロードのパーセンテージ (1%、2%、3% など) を進行状況バーに表示し、テキストとして表示する必要があります。しかし、ダウンロードごとに(1つのファイルのみ)、大量のダウンロード率(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...";
}
}
これを使用して、ダウンロードのすべての進捗率を取得するにはどうすればよいですか...? またはこれを行うための他の最良の方法...?