/// <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); }
/// <summary> /// download a file /// </summary> /// <param name="fileUrl">fileUrl</param> /// <param name="destinationFile">file's destination</param> /// <param name="downloadProgress">a action that can show the download progress</param> /// <param name="priority">background transfer priority </param> /// <param name="requestUnconstrainedDownload"></param> /// <returns></returns> public static async Task DownLoadSingleFileAsync(string fileUrl, IStorageFile destinationFile, Action<DownloadOperation> downloadProgress =null , BackgroundTransferPriority priority = BackgroundTransferPriority.Default, bool requestUnconstrainedDownload = false) { Uri source; if (!Uri.TryCreate(fileUrl, UriKind.Absolute, out source)) { // Logger.Info("File Url:" + fileUrl + "is not valid URIs"); Debug.WriteLine("File Url:" + fileUrl + "is not valid URIs"); return; } BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(source, destinationFile); download.Priority = priority; Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Downloading {0} to {1} with {2} priority, {3}", source.AbsoluteUri, destinationFile.Name, priority, download.Guid)); if (!requestUnconstrainedDownload) { // Attach progress and completion handlers. await HandleDownloadAsync(download, true, downloadProgress); return; } }
private async void StartDownload(Uri source, string destination, BackgroundTransferPriority priority) { StorageFile destinationFile; try { StorageFolder picturesLibrary = ApplicationData.Current.LocalFolder; destinationFile = await picturesLibrary.CreateFileAsync( destination, CreationCollisionOption.GenerateUniqueName); } catch (FileNotFoundException ex) { // rootPage.NotifyUser("Error while creating file: " + ex.Message, NotifyType.ErrorMessage); return; } BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(source, destinationFile); Log(String.Format(CultureInfo.CurrentCulture, "Downloading {0} to {1} with {2} priority, {3}", source.AbsoluteUri, destinationFile.Name, priority, download.Guid)); download.Priority = priority; // Attach progress and completion handlers. await HandleDownloadAsync(download, true); }
private async void StartDownload(BackgroundTransferPriority priority,bool requestUnconstrainedDownload,string downloadLink,string destination) { // Validating the URI is required since it was received from an untrusted source (user input). // The URI is validated by calling Uri.TryCreate() that will return 'false' for strings that are not valid URIs. // Note that when enabling the text box users may provide URIs to machines on the intrAnet that require // the "Home or Work Networking" capability. Uri source; if(!Uri.TryCreate(downloadLink,UriKind.Absolute,out source)) { Debug.WriteLine("Invalid URI."); return; } if(string.IsNullOrWhiteSpace(destination)) { Debug.WriteLine("A local file name is required."); return; } StorageFile destinationFile; try { destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync( destination, CreationCollisionOption.GenerateUniqueName); } catch(FileNotFoundException ex) { Debug.WriteLine("Error while creating file: " + ex.Message ); return; } BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(source,destinationFile); Debug.WriteLine(String.Format(CultureInfo.CurrentCulture,"Downloading {0} to {1} with {2} priority, {3}", source.AbsoluteUri,destinationFile.Name,priority,download.Guid)); download.Priority = priority; if(!requestUnconstrainedDownload) { // Attach progress and completion handlers. await HandleDownloadAsync(download,true); return; } List<DownloadOperation> requestOperations = new List<DownloadOperation>(); requestOperations.Add(download); // If the app isn't actively being used, at some point the system may slow down or pause long running // downloads. The purpose of this behavior is to increase the device's battery life. // By requesting unconstrained downloads, the app can request the system to not suspend any of the // downloads in the list for power saving reasons. // Use this API with caution since it not only may reduce battery life, but it may show a prompt to // the user. UnconstrainedTransferRequestResult result = await BackgroundDownloader.RequestUnconstrainedDownloadsAsync(requestOperations); Debug.WriteLine(String.Format(CultureInfo.CurrentCulture,"Request for unconstrained downloads has been {0}", (result.IsUnconstrained ? "granted" : "denied"))); await HandleDownloadAsync(download,true); }
/// <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) { try { 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 = KnownFolders.MusicLibrary; IReadOnlyList <StorageFolder> testlist = await storageFolder.GetFoldersAsync(); storageFolder = testlist[0]; var path = Global.Current.LocalSettings.LoadData("DownloadPath"); if (path != null) { if (path.ToString().Equals("SD")) { storageFolder = KnownFolders.RemovableDevices; IReadOnlyList <StorageFolder> folderList = await storageFolder.GetFoldersAsync(); for (int i = 0; i < folderList.Count; i++) { if (folderList[i].Attributes == FileAttributes.Directory) { storageFolder = folderList[i]; break; } } } } 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); } catch (Exception ex) { Debug.WriteLine(ex.Message); } }
private async void StartDownload(BackgroundTransferPriority priority,bool requestUnconstrainedDownload,string url,string fileNameField) { Uri source; if(!Uri.TryCreate(url.Trim(),UriKind.Absolute,out source)) { //rootPage.NotifyUser("Invalid URI.",NotifyType.ErrorMessage); return; } string destination = fileNameField.Trim() + ".zip"; if(string.IsNullOrWhiteSpace(destination)) { destination = fileNameField.Trim(); } StorageFile destinationFile; try { destinationFile = await KnownFolders.VideosLibrary.CreateFileAsync( destination, CreationCollisionOption.GenerateUniqueName); } catch { return; } BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(source,destinationFile); //Log(String.Format(CultureInfo.CurrentCulture,"Downloading {0} to {1} with {2} priority, {3}", // source.AbsoluteUri,destinationFile.Name,priority,download.Guid)); download.Priority = priority; if(!requestUnconstrainedDownload) { // Attach progress and completion handlers. await HandleDownloadAsync(download,true); return; } List<DownloadOperation> requestOperations = new List<DownloadOperation>(); requestOperations.Add(download); // If the app isn't actively being used, at some point the system may slow down or pause long running // downloads. The purpose of this behavior is to increase the device's battery life. // By requesting unconstrained downloads, the app can request the system to not suspend any of the // downloads in the list for power saving reasons. // Use this API with caution since it not only may reduce battery life, but it may show a prompt to // the user. UnconstrainedTransferRequestResult result = await BackgroundDownloader.RequestUnconstrainedDownloadsAsync(requestOperations); //Log(String.Format(CultureInfo.CurrentCulture,"Request for unconstrained downloads has been {0}", //(result.IsUnconstrained ? "granted" : "denied"))); await HandleDownloadAsync(download,true); }
private async Task <bool> StartDownload(BackgroundTransferPriority priority, string URL, string FileToSave) { Uri source; if (!Uri.TryCreate(URL, UriKind.Absolute, out source)) { return(true); } string destination; if (URL.Split('.').LastOrDefault() == "gif") { destination = FileToSave + ".gif"; } else { destination = FileToSave + ".png"; } StorageFile destinationFile; try { destinationFile = await _Folder.CreateFileAsync(destination, CreationCollisionOption.GenerateUniqueName); } catch (Exception ex) { return(true); } BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(source, destinationFile); download.Priority = priority; try { activeDownloads.Add(download); await download.StartAsync().AsTask(cts.Token); } catch (Exception) { } finally { activeDownloads.Remove(download); } return(true); }
private async void StartDownload(BackgroundTransferPriority priority) { // Validating the URI is required since it was received from an untrusted source (user input). // The URI is validated by calling Uri.TryCreate() that will return 'false' for strings that are not valid URIs. // Note that when enabling the text box users may provide URIs to machines on the intrAnet that require // the "Private Networks (Client and Server)" capability. Uri source; if (!Uri.TryCreate(serverAddressField.Text.Trim(), UriKind.Absolute, out source)) { rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage); return; } string destination = fileNameField.Text.Trim(); if (string.IsNullOrWhiteSpace(destination)) { rootPage.NotifyUser("A local file name is required.", NotifyType.ErrorMessage); return; } StorageFile destinationFile; try { StorageFolder picturesLibrary = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.PicturesLibrary); destinationFile = await picturesLibrary.CreateFileAsync( destination, CreationCollisionOption.GenerateUniqueName); } catch (FileNotFoundException ex) { rootPage.NotifyUser("Error while creating file: " + ex.Message, NotifyType.ErrorMessage); return; } BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(source, destinationFile); Log(String.Format(CultureInfo.CurrentCulture, "Downloading {0} to {1} with {2} priority, {3}", source.AbsoluteUri, destinationFile.Name, priority, download.Guid)); download.Priority = priority; // Attach progress and completion handlers. await HandleDownloadAsync(download, true); }
private static async Task StartDownload(Uri target, BackgroundTransferPriority priority, string localFilename) { var result = await BackgroundExecutionManager.RequestAccessAsync(); StorageFile destinationFile; destinationFile = await GetLocalFileFromName(localFilename); var group = BackgroundTransferGroup.CreateGroup(Guid.NewGuid().ToString()); group.TransferBehavior = BackgroundTransferBehavior.Serialized; BackgroundTransferCompletionGroup completionGroup = new BackgroundTransferCompletionGroup(); // this will cause the app to be activated when the download completes and // CheckCompletionResult will be called for the final download state RegisterBackgroundTask(completionGroup.Trigger); BackgroundDownloader downloader = new BackgroundDownloader(completionGroup); downloader.TransferGroup = group; group.TransferBehavior = BackgroundTransferBehavior.Serialized; CreateNotifications(downloader); DownloadOperation download = downloader.CreateDownload(target, destinationFile); download.Priority = priority; completionGroup.Enable(); Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress); var downloadTask = download.StartAsync().AsTask(progressCallback); string tag = GetFileNameFromUri(target); CreateToast(tag, localFilename); try { await downloadTask; // Will occur after download completes ResponseInformation response = download.GetResponseInformation(); } catch (Exception) { Debug.WriteLine("Download exception"); } }
public async void StartDownload( StorageFile destinationFile, string url, IProgress <double>?progress = null, BackgroundTransferPriority priority = BackgroundTransferPriority.Default) { if (!Uri.TryCreate(url, UriKind.Absolute, out Uri source)) { return; } BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(source, destinationFile); download.Priority = priority; if (progress != null) { _activeProgress.TryAdd(destinationFile.Path, progress); } await HandleDownloadAsync(download, true); }
private async void StartDownload(BackgroundTransferPriority priority) { // Validating the URI is required since it was received from an untrusted source (user input). // The URI is validated by calling Uri.TryCreate() that will return 'false' for strings that are not valid URIs. // Note that when enabling the text box users may provide URIs to machines on the intrAnet that require // the "Home or Work Networking" capability. Uri source; if (!Uri.TryCreate(serverAddressField.Text.Trim(), UriKind.Absolute, out source)) { rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage); return; } string destination = fileNameField.Text.Trim(); if (string.IsNullOrWhiteSpace(destination)) { rootPage.NotifyUser("A local file name is required.", NotifyType.ErrorMessage); return; } StorageFile destinationFile; try { destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync( destination, CreationCollisionOption.GenerateUniqueName); } catch (FileNotFoundException ex) { rootPage.NotifyUser("Error while creating file: " + ex.Message, NotifyType.ErrorMessage); return; } BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(source, destinationFile); Log(String.Format(CultureInfo.CurrentCulture, "Downloading {0} to {1} with {2} priority, {3}", source.AbsoluteUri, destinationFile.Name, priority, download.Guid)); download.Priority = priority; // Attach progress and completion handlers. await HandleDownloadAsync(download, true); }
public async void ContinueFolderPicker(Windows.ApplicationModel.Activation.FolderPickerContinuationEventArgs args) { // In this sample, we just use the default priority. // For more information about background transfer, please refer to the SDK Background transfer sample: // http://code.msdn.microsoft.com/windowsapps/Background-Transfer-Sample-d7833f61 BackgroundTransferPriority priority = BackgroundTransferPriority.Default; bool requestUnconstrainedDownload = false; StorageFolder destinationFolder = args.Folder; if (destinationFolder != null) { // Application now has read/write access to all contents in the picked folder // (including other sub-folder contents) StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", destinationFolder); Log("Picked folder: " + destinationFolder.Name); } else { Log("Operation cancelled."); return; } String localFileName = FileNameField.Text.Trim(); String ext = Path.GetExtension(localFileName); if (!String.Equals(ext, ".zip", StringComparison.OrdinalIgnoreCase)) { NotifyUser("Invalid file type. Please make sure the file type is zip.", NotifyType.ErrorMessage); return; } try { StorageFile localFile = await destinationFolder.CreateFileAsync(localFileName, CreationCollisionOption.GenerateUniqueName); BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(m_source, localFile); Log(String.Format(System.Globalization.CultureInfo.CurrentCulture, "Downloading {0} to {1} with {2} priority, {3}", m_source.AbsoluteUri, destinationFolder.Name, priority, download.Guid)); download.Priority = priority; // In this sample, we do not show how to request unconstrained download. // For more information about background transfer, please refer to the SDK Background transfer sample: // http://code.msdn.microsoft.com/windowsapps/Background-Transfer-Sample-d7833f61 if (!requestUnconstrainedDownload) { // Attach progress and completion handlers. await HandleDownloadAsync(download, true); StorageFolder unzipFolder = await destinationFolder.CreateFolderAsync(Path.GetFileNameWithoutExtension(localFile.Name), CreationCollisionOption.GenerateUniqueName); await UnZipFileAsync(localFile, unzipFolder); return; } } catch (Exception ex) { LogStatus(ex.Message, NotifyType.ErrorMessage); } }
private async void StartDownload(BackgroundTransferPriority priority, bool requestUnconstrainedDownload) { // Validating the URI is required since it was received from an untrusted source (user input). // The URI is validated by calling Uri.TryCreate() that will return 'false' for strings that are not valid URIs. // Note that when enabling the text box users may provide URIs to machines on the intrAnet that require // the "Home or Work Networking" capability. Uri source; if (!Uri.TryCreate(serverAddressField.Text.Trim(), UriKind.Absolute, out source)) { rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage); return; } string destination = fileNameField.Text.Trim(); if (string.IsNullOrWhiteSpace(destination)) { rootPage.NotifyUser("A local file name is required.", NotifyType.ErrorMessage); return; } StorageFile destinationFile; try { destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync( destination, CreationCollisionOption.GenerateUniqueName); } catch (FileNotFoundException ex) { rootPage.NotifyUser("Error while creating file: " + ex.Message, NotifyType.ErrorMessage); return; } BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(source, destinationFile); Log(String.Format(CultureInfo.CurrentCulture, "Downloading {0} to {1} with {2} priority, {3}", source.AbsoluteUri, destinationFile.Name, priority, download.Guid)); download.Priority = priority; if (!requestUnconstrainedDownload) { // Attach progress and completion handlers. await HandleDownloadAsync(download, true); return; } List <DownloadOperation> requestOperations = new List <DownloadOperation>(); requestOperations.Add(download); // If the app isn't actively being used, at some point the system may slow down or pause long running // downloads. The purpose of this behavior is to increase the device's battery life. // By requesting unconstrained downloads, the app can request the system to not suspend any of the // downloads in the list for power saving reasons. // Use this API with caution since it not only may reduce battery life, but it may show a prompt to // the user. UnconstrainedTransferRequestResult result; try { result = await BackgroundDownloader.RequestUnconstrainedDownloadsAsync(requestOperations); } catch (NotImplementedException) { rootPage.NotifyUser( "BackgroundDownloader.RequestUnconstrainedDownloadsAsync is not supported in Windows Phone.", NotifyType.ErrorMessage); return; } Log(String.Format(CultureInfo.CurrentCulture, "Request for unconstrained downloads has been {0}", (result.IsUnconstrained ? "granted" : "denied"))); await HandleDownloadAsync(download, true); }
private async void StartDownload(BackgroundTransferPriority priority, bool requestUnconstrainedDownload) { // The URI is validated by calling Uri.TryCreate() that will return 'false' for strings that are not valid URIs. // Note that when enabling the text box users may provide URIs to machines on the intrAnet that require // the "Home or Work Networking" capability. Uri source; if (!Uri.TryCreate(this.ZipFileUrlTextBox.Text.Trim(), UriKind.Absolute, out source)) { NotifyUser("Invalid URI.", NotifyType.ErrorMessage); return; } FolderPicker folderPicker = new FolderPicker(); folderPicker.SuggestedStartLocation = PickerLocationId.Downloads; folderPicker.FileTypeFilter.Add(".zip"); StorageFolder destinationFolder = await folderPicker.PickSingleFolderAsync(); if (destinationFolder != null) { // Application now has read/write access to all contents in the picked folder // (including other sub-folder contents) StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", destinationFolder); Log("Picked folder: " + destinationFolder.Name); } else { Log("Operation cancelled."); return; } String localFileName = FileNameField.Text.Trim(); String ext = Path.GetExtension(localFileName); if (!String.Equals(ext, ".zip", StringComparison.OrdinalIgnoreCase)) { NotifyUser("Invalid file type. Please make sure the file type is zip.", NotifyType.ErrorMessage); return; } try { StorageFile localFile = await destinationFolder.CreateFileAsync(localFileName, CreationCollisionOption.GenerateUniqueName); BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(source, localFile); Log(String.Format(System.Globalization.CultureInfo.CurrentCulture, "Downloading {0} to {1} with {2} priority, {3}", source.AbsoluteUri, destinationFolder.Name, priority, download.Guid)); download.Priority = priority; // In this sample, we do not show how to request unconstrained download. // For more information about background transfer, please refer to the SDK Background transfer sample: // http://code.msdn.microsoft.com/windowsapps/Background-Transfer-Sample-d7833f61 if (!requestUnconstrainedDownload) { // Attach progress and completion handlers. await HandleDownloadAsync(download, true); StorageFolder unzipFolder = await destinationFolder.CreateFolderAsync(Path.GetFileNameWithoutExtension(localFile.Name), CreationCollisionOption.GenerateUniqueName); await UnZipFileAsync(localFile, unzipFolder); return; } } catch (Exception ex) { LogStatus(ex.Message, NotifyType.ErrorMessage); } }