我可以通过这段代码将文件下载到SD卡中>
DownloadOperation downloadOperation;
CancellationTokenSource cancellationToken;
BackgroundDownloader backgroundDownloader = new BackgroundDownloader();
async private void ButtonDownload_Click(object sender, RoutedEventArgs e)
{
StorageFolder externalDevices = Windows.Storage.KnownFolders.RemovableDevices;
StorageFolder sdCard = (await externalDevices.GetFoldersAsync()).FirstOrDefault();
if (sdCard != null)
{
StorageFile file = await sdCard.CreateFileAsync("Downloads\\d460809d2cef1.pdf", CreationCollisionOption.GenerateUniqueName);
downloadOperation = backgroundDownloader.CreateDownload(new Uri("http://dowmain.com/uploads/d460809d2cef1.pdf"), file);
CancellationTokenSource cts = new CancellationTokenSource();
Progress<DownloadOperation> progress = new Progress<DownloadOperation>(progressChanged);
cancellationToken = new CancellationTokenSource();
try
{
await downloadOperation.StartAsync().AsTask(cancellationToken.Token, progress);
}
catch (TaskCanceledException)
{
TextBlockStatus.Text = "Download canceled.";
downloadOperation.ResultFile.DeleteAsync();
downloadOperation = null;
}
}
}
private void progressChanged(DownloadOperation downloadOperation)
{
int progress = (int)(100 * ((double)downloadOperation.Progress.BytesReceived / (double)downloadOperation.Progress.TotalBytesToReceive));
TextBlockProgress.Text = String.Format("{0} of {1} kb. downloaded - %{2} complete.", downloadOperation.Progress.BytesReceived / 1024, downloadOperation.Progress.TotalBytesToReceive / 1024, progress);
ProgressBarDownload.Value = progress;
switch (downloadOperation.Progress.Status)
{
case BackgroundTransferStatus.Running:
{
TextBlockStatus.Text = "Downloading...";
ButtonPauseResume.Content = "Pause";
break;
}
case BackgroundTransferStatus.PausedByApplication:
{
TextBlockStatus.Text = "Download paused.";
ButtonPauseResume.Content = "Resume";
break;
}
case BackgroundTransferStatus.PausedCostedNetwork:
{
TextBlockStatus.Text = "Download paused because of metered connection.";
ButtonPauseResume.Content = "Resume";
break;
}
case BackgroundTransferStatus.PausedNoNetwork:
{
TextBlockStatus.Text = "No network detected. Please check your internet connection.";
break;
}
case BackgroundTransferStatus.Error:
{
TextBlockStatus.Text = "An error occured while downloading.";
break;
}
}
if (progress >= 100)
{
TextBlockStatus.Text = "Download complete.";
downloadOperation = null;
}
}
我有两个问题:
- 我想下载多个文件并显示过程,但我不知道该怎么做。你能给我一个解决方案或源代码吗?
- 我可以访问 SD 卡进行下载,但如何将文件下载到我的手机内存中?
最佳答案
您的文件下载代码工作正常。但是这里不会持续更新状态,
对于您的第二个问题,您可以使用此工具将您的 pdf 文件下载到 Windows Phone 存储中。
StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
var file= await storageFolder.CreateFileAsync("fileName", CreationCollisionOption.GenerateUniqueName);
其他的事情将保持不变。 希望这会奏效,
关于c# - 在 Windows Phone 中使用 Background Downloader 进行多次下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28077799/