public async void CreateDownload(Uri uri, string destFileName) { StorageFile destinationFile = await downloadFolder.CreateFileAsync(destFileName, CreationCollisionOption.GenerateUniqueName); DownloadOperation download = downloader.CreateDownload(uri, destinationFile); Task <DownloadOperation> startTask = download.StartAsync().AsTask(); //startTask.ContinueWith(ForegroundCompletionHandler); downloader.CompletionGroup.Enable(); }
private async Task Run() { if (_downloadOperation != null) { _cancellationToken = new CancellationTokenSource(); await _downloadOperation.AttachAsync().AsTask(_cancellationToken.Token); } else { string fullPath = AddBackslash(RemoteFile.Path); fullPath += RemoteFile.Name; BackgroundDownloader downloader = new BackgroundDownloader(); downloader.SetRequestHeader("Authorization", "Bearer " + RemoteFile.Account.Token); _downloadOperation = downloader.CreateDownload(new Uri("https://graph.microsoft.com/v1.0/me" + fullPath + ":/content"), _loсalFile); _cancellationToken = new CancellationTokenSource(); _proccessId = _downloadOperation.Guid.GetHashCode(); await _downloadOperation.StartAsync().AsTask(_cancellationToken.Token); } try { StorageApplicationPermissions.FutureAccessList.Remove(_localFileToken); } catch (Exception e) { } }
protected override async Task <HttpTransfer> CreateDownload(HttpTransferRequest request) { var task = new BackgroundDownloader { Method = request.HttpMethod.Method, CostPolicy = request.UseMeteredConnection ? BackgroundTransferCostPolicy.Default : BackgroundTransferCostPolicy.UnrestrictedOnly }; foreach (var header in request.Headers) { task.SetRequestHeader(header.Key, header.Value); } if (!request.LocalFile.Exists) { request.LocalFile.Create(); } var winFile = await StorageFile.GetFileFromPathAsync(request.LocalFile.FullName).AsTask(); var operation = task.CreateDownload(new Uri(request.Uri), winFile); operation.StartAsync(); return(operation.FromNative()); }
public async Task DownloadAsync() { Uri source = new Uri(url); var localFolder = ApplicationData.Current.LocalFolder; StorageFile destinationFile = await localFolder.CreateFileAsync( name + ".mp3", CreationCollisionOption.GenerateUniqueName); BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(source, destinationFile); await download.StartAsync(); while (download.Progress.Status != BackgroundTransferStatus.Completed) { } var existingFile = await localFolder.TryGetItemAsync("PodcastDB.db"); var conString = "Data Source=" + existingFile.Path + ";"; var cmdString = "UPDATE Episodes " + "SET Status = 'Downloaded' " + "WHERE Title = '" + name + "'"; SqliteConnection cn = new SqliteConnection(conString); SqliteCommand cmd = new SqliteCommand(cmdString, cn); cn.Open(); cmd.ExecuteNonQuery(); cn.Close(); }
/// <summary> /// Download a single file directly. /// </summary> private async void DownloadFTPFileAsync( BackgroundDownloader downloader, NetworkCredential credential, FTPFileSystem item, StorageFile targetFile) { if (item.Size > 1048576) // 1M Byte { Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress); Uri urlWithCredential = item.Url; if (credential != null) { urlWithCredential = new Uri(item.Url.ToString().ToLower().Replace(@"ftp://", string.Format(@"ftp://{0}:{1}@", FTPFileSystem.EncodeUrl(credential.UserName), FTPFileSystem.EncodeUrl(credential.Password)))); } DownloadOperation download = downloader.CreateDownload( urlWithCredential, targetFile); ActiveBackgroundDownloaders.Add(download); await download.StartAsync().AsTask(progressCallback); } else { await FTPClient.DownloadFTPFileAsync(item, targetFile, credential) .ContinueWith(new Action<Task<DownloadCompletedEventArgs>>(DownloadProgress)); } }
private async Task TryScheduleAttachmentDownload(SignalAttachment attachment) { if (Downloads.Count < 100) { if (attachment.Status != SignalAttachmentStatus.Finished && !Downloads.ContainsKey(attachment.Id)) { SignalServiceAttachmentPointer attachmentPointer = attachment.ToAttachmentPointer(); IStorageFolder localFolder = ApplicationData.Current.LocalFolder; IStorageFile tmpDownload = await Task.Run(async() => { return(await ApplicationData.Current.LocalCacheFolder.CreateFileAsync(@"Attachments\" + attachment.Id + ".cipher", CreationCollisionOption.ReplaceExisting)); }); BackgroundDownloader downloader = new BackgroundDownloader(); downloader.SetRequestHeader("Content-Type", "application/octet-stream"); // this is the recommended way to call CreateDownload // see https://docs.microsoft.com/en-us/uwp/api/windows.networking.backgroundtransfer.backgrounddownloader#Methods DownloadOperation download = downloader.CreateDownload(new Uri(await MessageReceiver.RetrieveAttachmentDownloadUrl(CancelSource.Token, attachmentPointer)), tmpDownload); attachment.Guid = download.Guid.ToString(); SignalDBContext.UpdateAttachmentGuid(attachment); Downloads.Add(attachment.Id, download); var downloadSuccessfulHandler = Task.Run(async() => { Logger.LogInformation("Waiting for download {0}({1})", attachment.SentFileName, attachment.Id); var t = await download.StartAsync(); await HandleSuccessfullDownload(attachment, tmpDownload, download); }); } } }
public async Task DownloadAsync(Uri uri, StorageFile destination) { var downloader = new BackgroundDownloader(); var download = downloader.CreateDownload(uri, destination); await download.StartAsync(); }
private async void GetUrl(string linkf, string name) { try { StorageFile destinationFile; StorageFolder fd = await ApplicationData.Current.LocalFolder.CreateFolderAsync("shared", CreationCollisionOption.OpenIfExists); StorageFolder fd2 = await fd.CreateFolderAsync("transfers", CreationCollisionOption.OpenIfExists); destinationFile = await fd2.CreateFileAsync(name.Replace("(", "- ").Replace(")", "").Replace("/", "-").Replace(".", "-") + ".mp4", CreationCollisionOption.GenerateUniqueName); //destinationFile = await KnownFolders.MusicLibrary.CreateFileAsync("love.mp3", CreationCollisionOption.GenerateUniqueName); BackgroundDownloader backgroundDownloader = new BackgroundDownloader(); DownloadOperation download = backgroundDownloader.CreateDownload(new Uri("http://www.phimmoi.net/player.php?url=" + linkf.Replace("\\/", "/"), UriKind.RelativeOrAbsolute), destinationFile); ToastPrompt tost = new ToastPrompt() { Title = "Success:", Message = "This file starting download." }; tost.Show(); await download.StartAsync(); } catch { ToastPrompt tost = new ToastPrompt() { Title = "Error:", Message = "have a problem when start downloading, please try again!" }; tost.Show(); //Toast2.Message = "have a problem when start downloading, please try again!"; } }
private async System.Threading.Tasks.Task StartDownload() { String inputURL = queryURL.Text; if (inputURL.Length == 0) { return; } try { errlog.Text = "文件开始下载,请耐心等待"; Uri source = new Uri(inputURL); StorageFile destinationFile = await KnownFolders.MusicLibrary.CreateFileAsync( RandomString(4) + ".mp3", CreationCollisionOption.GenerateUniqueName); BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(source, destinationFile); await download.StartAsync(); // Attach progress and completion handlers. errlog.Text = "文件下载完成,马上开始播放"; player.Source = MediaSource.CreateFromStorageFile(destinationFile); player.MediaPlayer.Play(); } catch (Exception ex) { errlog.Text = "文件下载失败,请检查输入网址是否错误"; } }
private async void btStartDownload(object sender, RoutedEventArgs e) { tempDestinationFile = await tempFolder.CreateFileAsync("tempDownload", CreationCollisionOption.ReplaceExisting); BackgroundDownloader downloader = new BackgroundDownloader(); DownloadFile = downloader.CreateDownload(new Uri(txbDownloadLink.Text), tempDestinationFile); Progress <DownloadOperation> progress = new Progress <DownloadOperation>(progressChangedAsync); cancellationToken = new CancellationTokenSource(); try { txbFileName.Visibility = Visibility.Collapsed; tbFileName.Visibility = Visibility.Visible; tbSize.Text = "Initializing..."; btPause.IsEnabled = false; tsDownload.IsOn = true; tbFileName.Text = txbFileName.Text; await DownloadFile.StartAsync().AsTask(cancellationToken.Token, progress); } catch (TaskCanceledException) { CleanUpDownloadLeftOver(); } catch (Exception) { CleanUpDownloadLeftOver(); UtilityClass.MessageDialog("Error Occured while downloading file, Please Try again", "Error"); } }
//downloads a file given the Download file public async Task <StorageFile> DownloadFileAsync(Download download) { //initiate a blank file StorageFile file = null; //ensure that provided Download is not empty if (download != null) { //create file in downloads folder, ensure file renames if there's a duplicate file = await DownloadsFolder.CreateFileAsync(download.DownloadName, CreationCollisionOption.GenerateUniqueName); //create download operation downloadOperation = downloader.CreateDownload(download.DownloadUrl, file); //initiate cancellation token cancellationToken = new CancellationTokenSource(); try { //attempt to download file download.Status = "downloading"; await downloadOperation.StartAsync().AsTask(cancellationToken.Token); download.Status = "complete"; } catch (TaskCanceledException) { //if download fails delete file and release downloadOperation await downloadOperation.ResultFile.DeleteAsync(); downloadOperation = null; download.Status = "cancelled"; } } //if download is successful, return the downloaded file. return(file); }
private async Task <MediaSource> DownloadAndStartMusicFile(LibraryItem libraryItemToPlay) { string fileName = GetFileNameFromFullPath(libraryItemToPlay.FilePath); StorageFolder folderToSaveTo = await GetStorageFolderForItem(libraryItemToPlay); _logger.Information("Downloading music file {filePath}", libraryItemToPlay.FilePath); CurrentlyPlayingItemThumbnail = null; Uri downloadUri = GetUri(libraryItemToPlay); StorageFile downloadFile = await folderToSaveTo.CreateFileAsync(fileName); DownloadInProgress = true; BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(downloadUri, downloadFile); download.IsRandomAccessRequired = true; UpdateDownloadStatusOnUiThread(0, "Starting download..."); Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(HandleDownloadProgress); Task <DownloadOperation> downloadTask = download.StartAsync().AsTask(progressCallback); MediaSource mediaSource = MediaSource.CreateFromDownloadOperation(download); MediaPlaybackItem mediaPlaybackItem = new MediaPlaybackItem(mediaSource); _mediaPlayer.Source = mediaPlaybackItem; await UpdateSystemMediaTransportControlsAndThumbnail(libraryItemToPlay, mediaPlaybackItem); await downloadTask; DownloadInProgress = false; return(mediaSource); }
async void CreateDownload() { label0 :; string str; if (vi.type == 1) { str = vi.href; } else { str = vi.href + (part + 1).ToString() + vi.vkey; } StorageFile ss = await sf.CreateFileAsync(part.ToString(), CreationCollisionOption.ReplaceExisting); down = BD.CreateDownload(new Uri(str), ss); try { await down.StartAsync(); miss.downindex = part; }catch (Exception ex) { } part++; if (part < miss.max) { goto label0; } callback(miss); }
internal async Task BackgroundDownload() { if (SelectedItem == null) { await new MessageDialog("No File Selected").ShowAsync(); } FileSavePicker fileSavePicker = new FileSavePicker(); fileSavePicker.SuggestedFileName = SelectedItem.Name; var ext = Path.GetExtension(SelectedItem.Name); fileSavePicker.FileTypeChoices.Add(ext, new string[] { ext }); StorageFile saveFile = await fileSavePicker.PickSaveFileAsync(); if (saveFile == null) { return; } var bgDownloader = new BackgroundDownloader(); var test = Path.Combine(Config.FilesEndpointUri.ToString(), string.Format(Constants.ContentPathString, SelectedItem.Id)); bgDownloader.SetRequestHeader(Constants.AuthHeaderKey, string.Format(Constants.V2AuthString, Client.Auth.Session.AccessToken)); var download = bgDownloader.CreateDownload(new Uri(test), saveFile); var testRes = await download.StartAsync(); }
private async void downloadButton_Click(object sender, RoutedEventArgs e) { if (fileUrl.Text == "") { info.Text = "文件地址不能为空"; return; } string transferFileName = fileUrl.Text; string downloadFile = DateTime.Now.Ticks + transferFileName.Substring(transferFileName.LastIndexOf("/") + 1); Uri transferUri; try { transferUri = new Uri(Uri.EscapeUriString(transferFileName), UriKind.RelativeOrAbsolute); } catch (Exception ex) { info.Text = "文件地址不符合格式"; return; } StorageFile destinationFile; StorageFolder fd = await ApplicationData.Current.LocalFolder.CreateFolderAsync("shared", CreationCollisionOption.OpenIfExists); StorageFolder fd2 = await fd.CreateFolderAsync("transfers", CreationCollisionOption.OpenIfExists); destinationFile = await fd2.CreateFileAsync(downloadFile, CreationCollisionOption.ReplaceExisting); BackgroundDownloader backgroundDownloader = new BackgroundDownloader(); DownloadOperation download = backgroundDownloader.CreateDownload(transferUri, destinationFile); await download.StartAsync(); }
public async static Task <string> CoverPlaylistById(long playlistId, string uriImage) { StorageFile coverFile; try { coverFile = await StaticContent.CoversFolder.GetFileAsync($"VK{playlistId}Playlist.jpg"); } catch { if (config.SaveImage) { var task = Task.Run(async() => { coverFile = await StaticContent.CoversFolder.CreateFileAsync($"VK{playlistId}Playlist.jpg"); BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(new Uri(uriImage), coverFile); await download.StartAsync(); }); } return(uriImage); } return(coverFile.Path); }
private async void StartDownloadsButton_Click(object sender, RoutedEventArgs e) { Uri baseUri; if (!Uri.TryCreate(serverAddressField.Text.Trim(), UriKind.Absolute, out baseUri)) { rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage); return; } BackgroundDownloader downloader = CompletionGroupTask.CreateBackgroundDownloader(); downloadsCompleted = 0; for (int i = 0; i < 10; i++) { Uri uri = new Uri(baseUri, String.Format(CultureInfo.InvariantCulture, "?id={0}", i)); DownloadOperation download = downloader.CreateDownload(uri, await CreateResultFileAsync(i)); Task <DownloadOperation> startTask = download.StartAsync().AsTask(); Task continueTask = startTask.ContinueWith(OnDownloadCompleted); } downloader.CompletionGroup.Enable(); SetSubstatus("Completion group enabled."); }
public async static Task <string> BannerArtist(string url) { StorageFile bannerArtist; try { bannerArtist = await StaticContent.CoversFolder.GetFileAsync($"Artist{url.GetHashCode()}Banner.jpg"); } catch { if (config.SaveImage) { var a = Task.Run(async() => { bannerArtist = await StaticContent.CoversFolder.CreateFileAsync($"Artist{url.GetHashCode()}Banner.jpg"); BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(new Uri(url), bannerArtist); await download.StartAsync(); }); } return(url); } return(bannerArtist.Path); }
public async void DownloadZipFile(string fileurl, IPromise promise) { try { var newFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("ZipFolder", CreationCollisionOption.ReplaceExisting); var file = await newFolder.CreateFileAsync("sample1.pdf", CreationCollisionOption.ReplaceExisting); Uri source = new Uri(fileurl); BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(source, file); download.CostPolicy = BackgroundTransferCostPolicy.Always; download.Priority = BackgroundTransferPriority.High; var success = await download.StartAsync(); if (file != null) { promise.Resolve(null); } else { promise.Reject(null, "File Copied failed."); } } catch (Exception e) { Console.WriteLine("Excep===>" + e); // promise.Reject(null, fileurl, e); } }
private async Task SaveMultipleImagesAsync(Uri uriAddress) { var destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync("image.png", CreationCollisionOption.GenerateUniqueName); BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation downloadOperation = downloader.CreateDownload(uriAddress, destinationFile); // Define the cancellation token. CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken token = cts.Token; // Time out after 5000 milliseconds cts.CancelAfter(5000); try { // Pass the token to the task that listens for cancellation. await downloadOperation.StartAsync().AsTask(token); // file is downloaded in time } catch (TaskCanceledException) { // timeout is reached, downloadOperation is cancled } finally { // Releases all resources of cts cts.Dispose(); } }
private async void Start_Click(object sender, RoutedEventArgs e) { BackgroundDownloader downloader = CreateDownloader(); try { IStorageFile file = await KnownFolders.PicturesLibrary.CreateFileAsync("downloadFile.txt", CreationCollisionOption.GenerateUniqueName); Uri uri = new Uri(UriBox.Text); slowDownload = downloader.CreateDownload(uri, file); downloadCancellationTokenSource = new CancellationTokenSource(); ProgressBlock.Text = String.Empty; StartBlock.Text = String.Format("Guid: {0}\r\nPath: {1}", slowDownload.Guid, slowDownload.ResultFile.Path); HeadersBlock.Text = String.Empty; Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(OnDownloadProgress); var task = slowDownload.StartAsync().AsTask(downloadCancellationTokenSource.Token, progressCallback); var notAwaited = task.ContinueWith(OnDownloadCompleted, slowDownload); } catch (Exception ex) { DisplayException(ex); } }
/// <summary> /// 返回指定参数的下载操作 /// </summary> /// <param name="url">请求到的下载地址</param> /// <param name="name">要下载的文件名</param> /// <returns></returns> static public async Task <DownloadOperation> Download(string url, string name, StorageFolder folder) { try { BackgroundDownloader downloader = new BackgroundDownloader(); Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(KnownFolders.VideosLibrary); StorageFile file = await folder.CreateFileAsync(name, CreationCollisionOption.GenerateUniqueName); DownloadOperation download = downloader.CreateDownload(new Uri(url), file); if (SettingHelper.ContainsKey("_downloadcost")) { if (SettingHelper.GetValue("_downloadcost").ToString() == "wifionly") { download.CostPolicy = BackgroundTransferCostPolicy.UnrestrictedOnly; } else if (SettingHelper.GetValue("_downloadcost").ToString() == "wifidata") { download.CostPolicy = BackgroundTransferCostPolicy.Default; } } return(download); } catch (Exception ex) { var a = ex.Message; return(null); //WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult); //MessageDialog md = new MessageDialog(ex.Message); //await md.ShowAsync(); } }
public async Task DownloadFullImageAsync(CancellationToken token) { var url = GetSaveImageUrlFromSettings(); if (string.IsNullOrEmpty(url)) { return; } ToastService.SendToast("Downloading in background...", 2000); StorageFolder folder = await AppSettings.Instance.GetSavingFolderAsync(); var fileName = $"{Owner.Name} {CreateTimeString}"; var newFile = await folder.CreateFileAsync($"{fileName}.jpg", CreationCollisionOption.GenerateUniqueName); _backgroundDownloader.SuccessToastNotification = ToastHelper.CreateToastNotification("Saved:D", $"Tap to open {folder.Path}."); var downloadOperation = _backgroundDownloader.CreateDownload(new Uri(url), newFile); var progress = new Progress <DownloadOperation>(); try { await downloadOperation.StartAsync().AsTask(token, progress); } catch (TaskCanceledException) { await downloadOperation.ResultFile.DeleteAsync(); downloadOperation = null; throw; } }
// Loading changing and uploading counter from server private async void button2_Click(object sender, RoutedEventArgs e) { if (OwnSemaphoreBtn2 == true) { OwnSemaphoreBtn2 = false; textBlock1.Text = "загрузка"; StorageFile myDB; try { string address = @"http://artmordent.ru/cheataxi/database.cr"; StorageFile tempFile2 = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("database", CreationCollisionOption.ReplaceExisting); BackgroundDownloader manager2 = new BackgroundDownloader(); var operation = manager2.CreateDownload(new Uri(address), tempFile2); IProgress <DownloadOperation> progressH = new Progress <DownloadOperation>((p) => { Debug.WriteLine("Transferred: {0}, Total: {1}", p.Progress.BytesReceived, p.Progress.TotalBytesToReceive); }); await operation.StartAsync().AsTask(progressH); Debug.WriteLine("BacgroundTransfer created"); myDB = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("database"); string s = await Windows.Storage.FileIO.ReadTextAsync(myDB); int num; if (Int32.TryParse(s, out num)) { } else /*Error*/ } { textBlock1.Text = (++num).ToString(); var Successful = await LoadFunctions.SmallUpload("ftp://artmordent.ru/", "database.cr", "voropash_2", "123456789", num.ToString()); await myDB.DeleteAsync(); }
private static async Task <StorageFile> SaveFileFromUriAsync(Uri fileUri, string localFileName, string localPath = "Images", NameCollisionOption collisionOption = NameCollisionOption.ReplaceExisting) { if (localFileName.StartsWith("/")) { localFileName = localFileName.Substring(1); } localFileName = Path.GetFileName(localFileName); var destinationFolder = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync(localPath, CreationCollisionOption.OpenIfExists); var outFile = await destinationFolder.CreateFileAsync(localFileName, CreationCollisionOption.OpenIfExists); if ((await outFile.GetBasicPropertiesAsync()).Size == 0) { BackgroundDownloader backgroundDownloader = new BackgroundDownloader(); var download = backgroundDownloader.CreateDownload(fileUri, outFile); try { download.CostPolicy = BackgroundTransferCostPolicy.Always; var downloadTask = download.StartAsync(); await downloadTask; } catch { } } return(outFile); }
/// <summary> /// StartDownload /// </summary> /// <param name="url">Download url</param> /// <param name="priority"></param> /// <param name="saveStorage">default LocalFolder</param> public async void StartDownload(string url, BackgroundTransferPriority priority = BackgroundTransferPriority.Default, StorageFile saveStorage = null) { Uri uri = null; if (!Uri.TryCreate(url, UriKind.Absolute, out uri)) { if (this.ErrorException != null) { this.ErrorException(this, "Please Invalid DownloadURl"); } return; } if (priority == null) { priority = BackgroundTransferPriority.Default; } if (saveStorage == null) { var storageFolder = ApplicationData.Current.LocalFolder; saveStorage = await storageFolder.CreateFileAsync(conDefaultFileName, CreationCollisionOption.GenerateUniqueName); } BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(uri, saveStorage); download.Priority = priority; await this.HandleDownloadAsync(download, true); }
public async void DownloadVideo() { var client = new YoutubeClient(); var videoUrl = Constants.videoInfo.Muxed[0].Url; var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Downloads; savePicker.FileTypeChoices.Add("Video File", new List <string>() { ".mp4" }); Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { // Prevent updates to the remote version of the file until // we finish making changes and call CompleteUpdatesAsync. Windows.Storage.CachedFileManager.DeferUpdates(file); // write to file BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(new Uri(videoUrl), file); DownloadProgress.Visibility = Visibility.Visible; Progress <DownloadOperation> progress = new Progress <DownloadOperation>(); progress.ProgressChanged += Progress_ProgressChanged; await download.StartAsync().AsTask(CancellationToken.None, progress); } else { Log.Info("Download operation was cancelled."); } }
public static IAsyncAction Download(Uri fileUri) { return(Run(async token => { var d = new BackgroundDownloader { FailureToastNotification = failedToast }; var file = await DownloadsFolder.CreateFileAsync($"{fileUri.GetHashCode():X}.TsinghuaNet.temp", CreationCollisionOption.GenerateUniqueName); var downloadOperation = d.CreateDownload(fileUri, file); downloadOperation.StartAsync().Completed = async(sender, e) => { string name = null; var resI = downloadOperation.GetResponseInformation(); if (resI != null) { if (resI.Headers.TryGetValue("Content-Disposition", out name)) { var h = HttpContentDispositionHeaderValue.Parse(name); name = h.FileName; if (string.IsNullOrWhiteSpace(name)) { name = null; } } name = name ?? getFileNameFromUri(resI.ActualUri); } name = name ?? getFileNameFromUri(fileUri); name = toValidFileName(name); await file.RenameAsync(name, NameCollisionOption.GenerateUniqueName); var fToken = StorageApplicationPermissions.MostRecentlyUsedList.Add(file); NotificationService.NotificationService.SendToastNotification(LocalizedStrings.Toast.DownloadSucceed, name, handler, fToken); }; })); }
public async Task <StorageFile> Download(string url, string fileName, StorageFolder folder) { bool fileExist = false; StorageFile file = null; try { file = await folder.GetFileAsync(fileName); fileExist = true; } catch (Exception ex) { Debug.WriteLine(ex.Message); fileExist = false; } if (fileExist == false) { try { file = await folder.CreateFileAsync(fileName); var downloader = new BackgroundDownloader(); var operation = downloader.CreateDownload(new Uri(url), file); await operation.StartAsync(); } catch (Exception ex) { Debug.WriteLine(ex.Message); } } return(file); }
public async Task <List <DownloadOperation> > CreateDownloadAsync(List <BaseItem> items, StorageFolder folder) { List <DownloadOperation> result = new List <DownloadOperation>(); BackgroundDownloader downloader = new BackgroundDownloader(); downloader.ServerCredential = new PasswordCredential(Configuration.ServerUrl, Configuration.UserName, Configuration.Password); foreach (var davItem in items) { StorageFile file; Uri uri; if (davItem.IsCollection) { file = await folder.CreateFileAsync(davItem.DisplayName + ".zip", CreationCollisionOption.OpenIfExists); uri = new Uri(GetZipUrl(davItem.EntityId)); } else { file = await folder.CreateFileAsync(davItem.DisplayName, CreationCollisionOption.OpenIfExists); uri = new Uri(davItem.EntityId, UriKind.RelativeOrAbsolute); } result.Add(downloader.CreateDownload(CreateItemUri(uri), file)); } return(result); }