public async void Download() { FolderPicker folderPicker = new FolderPicker(); folderPicker.SuggestedStartLocation = PickerLocationId.Downloads; folderPicker.ViewMode = PickerViewMode.Thumbnail; folderPicker.FileTypeFilter.Add("*"); StorageFolder folder = await folderPicker.PickSingleFolderAsync(); if (folder != null) { StorageFile file = await folder.CreateFileAsync("Unplash-v2-Search.jpg", CreationCollisionOption.GenerateUniqueName); string a = itemDownv2.Content.ToString(); Uri durl = new Uri(a); downloadOperation = backgroundDownloader.CreateDownload(durl, file); Progress <DownloadOperation> progress = new Progress <DownloadOperation>(progressChanged); cancellationToken = new CancellationTokenSource(); try { //Statusring.IsActive = true; statusDownv2.Visibility = Visibility.Visible; await downloadOperation.StartAsync().AsTask(cancellationToken.Token, progress); } catch (TaskCanceledException) { downloadOperation.ResultFile.DeleteAsync(); downloadOperation = null; } } }
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> /// 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 getInfo() { StorageFile myDB; try { string address = @"http://artmordent.ru/cheataxi/multiplylines.cr"; StorageFile tempFile2 = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("info", CreationCollisionOption.ReplaceExisting); BackgroundDownloader manager2 = new BackgroundDownloader(); var operation = manager2.CreateDownload(new Uri(address), tempFile2); IProgress<DownloadOperation> progressH = new Progress<DownloadOperation>((p) => { }); await operation.StartAsync().AsTask(progressH); myDB = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("info"); // Read the data var alldata = await Windows.Storage.FileIO.ReadLinesAsync(myDB); string[] datalines = new string[alldata.Count]; Int32 ko = 0; foreach (var line in alldata) { datalines[ko] = line.ToString(); ko++; infoBlockMain.Text += line.ToString() + "\r\n"; } await myDB.DeleteAsync(); } catch (Exception ex) { MessageDialog dialog = new MessageDialog("Ошибка загрузки информации. Проверьте ваше соединение или попробуйте позже.", "Ошибка загрузки"); } }
//string imagerySet = MapType.Aerial.ToString(); public async Task<WriteableBitmap> RequestImage(Geopoint point) { if (geo == null) { geo = new Geolocator(); } Geoposition pos = await geo.GetGeopositionAsync(); //Geopoint point = pos.Coordinate.Point; myMap.Center = new Location(point.Position.Latitude, point.Position.Longitude); myMap.ZoomLevel = 2; myMap.Width = 100; this.myMap.Height = 100; string url = String.Format("http://dev.virtualearth.net/REST/v1/Imagery/Map/{0}/{1},{2}/{3}" + "?mapSize={4},{5}&key={6}", //imagerySet, this.myMap.Center.Latitude, this.myMap.Center.Longitude, Math.Floor(this.myMap.ZoomLevel), this.myMap.Width, this.myMap.Height, apiKey); var backgroundDownloader = new BackgroundDownloader(); var file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("tempmapimage.jpg", CreationCollisionOption.ReplaceExisting); var downloadOperation = backgroundDownloader.CreateDownload(new Uri(url), file); await downloadOperation.StartAsync(); return await BitmapFactory.New(1, 1).FromStream(await file.OpenReadAsync(), Windows.Graphics.Imaging.BitmapPixelFormat.Unknown); }
public static async Task<Episode> DownloadPodcastEpisodeAsync(Episode episode, Action<DownloadOperation> callback, Action errorCallback = null) { var appFolder = await KnownFolders.MusicLibrary.CreateFolderAsync("PodcastR", CreationCollisionOption.OpenIfExists); var podcastFolder = await appFolder.CreateFolderAsync(episode.Podcast.Name, CreationCollisionOption.OpenIfExists); try { var uri = new Uri(episode.WebPath); var extension = uri.AbsolutePath.GetExtension(); var fileName = (episode.Name + extension).RemoveIllegalPathChars().Replace(":", ""); var episodeFile = await podcastFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); var backgroundDownloader = new BackgroundDownloader(); var downloadOperation = backgroundDownloader.CreateDownload(uri, episodeFile); var progress = new Progress<DownloadOperation>(callback); downloads.Add(episode, downloadOperation); var cts = new CancellationTokenSource(); cancellationTokenSources.Add(episode, cts); await downloadOperation.StartAsync().AsTask(cts.Token, progress); downloads.Remove(episode); cancellationTokenSources.Remove(episode); episode.IsLocal = true; episode.WebPath = episodeFile.Path; return episode; } catch { if (errorCallback != null) errorCallback(); return episode; } }
public async void Download() { FolderPicker folderPicker = new FolderPicker(); folderPicker.SuggestedStartLocation = PickerLocationId.Downloads; folderPicker.ViewMode = PickerViewMode.Thumbnail; folderPicker.FileTypeFilter.Add("*"); StorageFolder folder = await folderPicker.PickSingleFolderAsync(); if (folder != null) { StorageFile file = await folder.CreateFileAsync("NewImage.jpg", CreationCollisionOption.GenerateUniqueName); Uri downloadUrl = new Uri(LinkBox.Text.ToString()); downloadOperation = backgroundDownloader.CreateDownload(downloadUrl, file); Progress <DownloadOperation> progress = new Progress <DownloadOperation>(x => ProgressChanged(downloadOperation)); cancellationToken = new CancellationTokenSource(); try { TextBlockStatus.Text = "Initializing..."; await downloadOperation.StartAsync().AsTask(cancellationToken.Token, progress); } catch (TaskCanceledException) { TextBlockStatus.Text = "Download canceled."; await downloadOperation.ResultFile.DeleteAsync(); downloadOperation = null; } } }
/* * private async void StartDownload() * { * try * { * Uri source = new Uri(Promotie.Kortingsbon); * StorageFile destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync( * "Kortingsbon" + this.Promotie.Onderneming.Naam , CreationCollisionOption.GenerateUniqueName); * * BackgroundDownloader downloader = new BackgroundDownloader(); * DownloadOperation download = downloader.CreateDownload(source, destinationFile); * * // Attach progress and completion handlers. * // HandleDownloadAsync(download, true); * await download.StartAsync(); * * } * catch (Exception ex) * { * Debug.WriteLine("Download Error", ex); * } * } */ public async void Download() { FolderPicker folderPicker = new FolderPicker(); folderPicker.SuggestedStartLocation = PickerLocationId.Downloads; folderPicker.ViewMode = PickerViewMode.Thumbnail; folderPicker.FileTypeFilter.Add("*"); StorageFolder folder = await folderPicker.PickSingleFolderAsync(); if (folder != null) { StorageFile file = await folder.CreateFileAsync("Kortingsbon.jpg", CreationCollisionOption.GenerateUniqueName); Uri downloadUrl = new Uri(Promotie.Kortingsbon); downloadOperation = backgroundDownloader.CreateDownload(downloadUrl, file); cancellationToken = new CancellationTokenSource(); await downloadOperation.StartAsync().AsTask(cancellationToken.Token); //create XML var toastXml = new XmlDocument(); toastXml.LoadXml("<toast><visual><binding template='ToastGeneric'>" + "<text>Download</text><text>Uw kortingsbon is gedownload</text> " + "</binding></visual></toast>"); //build toast var toast = new ToastNotification(toastXml); //show toast var notifier = ToastNotificationManager.CreateToastNotifier(); notifier.Show(toast); } }
public static async Task<bool> Download(Revista rev, Func<IStorageFile, Task> onSucess, Action<string> callBack, Action<double> progressHandler) { if(!HaveInternetConnection()) { callBack("Sem conexão à Internet"); return false; } BackgroundDownloader bg = new BackgroundDownloader(); var folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(RevistaControllerWrapper.FolderName, CreationCollisionOption.OpenIfExists); var file = await folder.CreateFileAsync(RevistaControllerWrapper.GetPdfName(rev), CreationCollisionOption.ReplaceExisting); DownloadHelper down = new DownloadHelper(); ; try { var d = bg.CreateDownload(RevistaController.Instance.GetDownloadFile(rev), file); await down.HandleDownloadAsync(d, true, onSucess, callBack, progressHandler); } catch { return false; } return true ; }
private async void Button_Click(object sender, RoutedEventArgs e) { var source = new Uri("http://download.thinkbroadband.com/5MB.zip", UriKind.Absolute); var destination = await KnownFolders .PicturesLibrary .CreateFileAsync("5MB.zip", CreationCollisionOption.GenerateUniqueName); var downloader = new BackgroundDownloader(); // Toast notification para sucesso var successToastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01); successToastXml.GetElementsByTagName("text").Item(0).InnerText = "Download Concluído."; var successToast = new ToastNotification(successToastXml); downloader.SuccessToastNotification = successToast; // Toast notification para falha var failureToastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01); failureToastXml.GetElementsByTagName("text").Item(0).InnerText = "Falha no download."; var failureToast = new ToastNotification(failureToastXml); downloader.FailureToastNotification = failureToast; var downloadOperation = downloader.CreateDownload(source, destination); downloadOperation.Priority = BackgroundTransferPriority.High; var progressCallback = new Progress<DownloadOperation>(DownloadProgress); await downloadOperation.StartAsync().AsTask(new CancellationToken(), progressCallback); ; }
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); }
public async void download(String url, Folder folder) { var uri = new Uri(url); var downloader = new BackgroundDownloader(); StorageFile file = await folder.CreateFileAsync("100MB.zip", CreationCollisionOption.ReplaceExisting); DownloadOperation download = downloader.CreateDownload(uri, file); download.StartAsync(); }
private async void DownloadClick(object sender, RoutedEventArgs e) { const string fileLocation = "http://www.vulcanlab.net/download/Release.rar"; var uri = new Uri(fileLocation); var downloader = new BackgroundDownloader(); StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("100MB.zip", CreationCollisionOption.ReplaceExisting); DownloadOperation download = downloader.CreateDownload(uri, file); await StartDownloadAsync(download); }
public async Task<StorageFile> DownloadFileAsync( string appFolderName, string folderName, string fileName, string fileUrl, Action<DownloadOperation> callback, Action<Exception> errorCallback = null) { var appFolder = await KnownFolders.MusicLibrary.CreateFolderAsync(appFolderName, CreationCollisionOption.OpenIfExists); var podcastFolder = await appFolder.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists); var uri = new Uri(fileUrl); var extension = uri.AbsolutePath.GetExtension(); var filename = (fileName + extension).RemoveIllegalPathChars(); try { var file = await podcastFolder.CreateFileAsync(filename, CreationCollisionOption.FailIfExists); var backgroundDownloader = new BackgroundDownloader(); var downloadOperation = backgroundDownloader.CreateDownload(uri, file); var progress = new Progress<DownloadOperation>(callback); downloads.Add(fileUrl, downloadOperation); var cts = new CancellationTokenSource(); cancellationTokenSources.Add(fileUrl, cts); await downloadOperation.StartAsync().AsTask(cts.Token, progress); downloads.Remove(fileUrl); cancellationTokenSources.Remove(fileUrl); return file; } catch (NullReferenceException ex) { if (errorCallback != null) errorCallback(ex); return null; } catch (Exception) { try { var file = await podcastFolder.GetFileAsync(filename); return file; } catch (Exception ex) { if (errorCallback != null) errorCallback(ex); return null; } } }
public async Task<string> GetAsync(string request) { var backgroundDownloader = new BackgroundDownloader(); var temporaryFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(Utils.TemporaryFile, CreationCollisionOption.OpenIfExists); var downloader = backgroundDownloader.CreateDownload( new Uri(request), temporaryFile); await downloader.StartAsync(); var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(Utils.TemporaryFile, CreationCollisionOption.OpenIfExists); return await FileIO.ReadTextAsync(file); }
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); }
/// <summary> /// 要下载调用这个方法 /// </summary> /// <param name="url">下载的文件网址的来源</param> /// <returns></returns> public static async Task Start(string filename,string url,DownloadType type,StorageFolder folder=null) { try { Uri uri = new Uri(Uri.EscapeUriString(url), UriKind.RelativeOrAbsolute); BackgroundDownloader downloader = new BackgroundDownloader(); if (folder==null) { folder = await KnownFolders.MusicLibrary.CreateFolderAsync("kgdownload", CreationCollisionOption.OpenIfExists); switch (type) { case DownloadType.song: folder = await folder.CreateFolderAsync("song", CreationCollisionOption.OpenIfExists); downloader.TransferGroup = BackgroundTransferGroup.CreateGroup("song"); break; case DownloadType.mv: folder = await folder.CreateFolderAsync("mv", CreationCollisionOption.OpenIfExists); downloader.TransferGroup = BackgroundTransferGroup.CreateGroup("mv"); break; case DownloadType.other: folder = await folder.CreateFolderAsync("other", CreationCollisionOption.OpenIfExists); downloader.TransferGroup = BackgroundTransferGroup.CreateGroup("other"); break; default: break; } }else { downloader.TransferGroup = BackgroundTransferGroup.CreateGroup("other"); } //string name = uri.ToString().Substring(uri.ToString().LastIndexOf("/"), uri.ToString().Length); string name = filename; StorageFile file = await folder.CreateFileAsync(name, CreationCollisionOption.GenerateUniqueName); downloader.FailureToastNotification = DownloadedToast.Done(filename, DownloadedToast.DownResult.Fa); downloader.SuccessToastNotification = DownloadedToast.Done(filename, DownloadedToast.DownResult.Su); var download = downloader.CreateDownload(new Uri(url), file); TransferModel transfer = new TransferModel(); transfer.DownloadOperation = download; transfer.Source = download.RequestedUri.ToString(); transfer.Destination = download.ResultFile.Path; transfer.BytesReceived = download.Progress.BytesReceived; transfer.TotalBytesToReceive = download.Progress.TotalBytesToReceive; transfer.Progress = 0; transfers.Add(transfer); Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress); download.StartAsync().AsTask(cancelToken.Token, progressCallback); } catch { await new MessageDialog("链接已失效!").ShowAsync(); } }
// 非同期ダウンロードする private async void Button_Click_1(object sender, RoutedEventArgs e) { // ダウンロードしたファイルの保存先を指定する var uri = new Uri("http://download.thinkbroadband.com/100MB.zip"); // var uri = new Uri("{バックグランドでダウンロードするファイルのURL}"); var file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("example.zip", Windows.Storage.CreationCollisionOption.ReplaceExisting); // バックグランドで非同期ダウンロードする var downloader = new Windows.Networking.BackgroundTransfer.BackgroundDownloader(); DownloadOperation downloadOperation = downloader.CreateDownload(uri, file); var progress = new Progress<DownloadOperation>(NotificationProgress); await downloadOperation.StartAsync().AsTask(progress); }
private async static Task<StorageFile> SaveAsync( Uri fileUri, StorageFolder folder, string fileName) { var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); var downloader = new BackgroundDownloader(); var download = downloader.CreateDownload( fileUri, file); var res = await download.StartAsync(); return file; }
public async static Task SaveAsync( Uri fileUri, StorageFolder folder, string fileName) { // Hitting System.UnauthorizedAccessException when the file already exists. // If they already have it, keep what is there. var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists); var downloader = new BackgroundDownloader(); var download = downloader.CreateDownload( fileUri, file); await download.StartAsync(); }
private async void getPlaceFromCoordinates(Windows.Foundation.Point pos) { // Get world coordinates myMap.TryPixelToLocation(pos, out location); myMap.SetView(location); // Form request string tmpSourseLoc = Convert.ToString(location.Latitude).Substring(0, Convert.ToString(location.Latitude).IndexOf(',')) + '.' + Convert.ToString(location.Latitude).Substring(Convert.ToString(location.Latitude).IndexOf(',') + 1, Convert.ToString(location.Latitude).Length - Convert.ToString(location.Latitude).IndexOf(',') - 1); tmpSourseLoc += "," + Convert.ToString(location.Longitude).Substring(0, Convert.ToString(location.Longitude).IndexOf(',')) + '.' + Convert.ToString(location.Longitude).Substring(Convert.ToString(location.Longitude).IndexOf(',') + 1, Convert.ToString(location.Longitude).Length - Convert.ToString(location.Longitude).IndexOf(',') - 1); string address = "http://geocode-maps.yandex.ru/1.x/?geocode=" + tmpSourseLoc + "&sco=latlong"; //log1.Text += address; StorageFile myDB; try { // Send request StorageFile tempFile2 = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("multi", 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"); // Write answer myDB = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("multi"); var alldata = await Windows.Storage.FileIO.ReadLinesAsync(myDB); datalines = new string[alldata.Count]; int ko = 0; int start; // Analise answer foreach (var line in alldata) { datalines[ko] = line.ToString(); ko++; if ((start = datalines[ko - 1].IndexOf("<text>")) != -1) { // Print adress int nameLeng = datalines[ko - 1].Length; if (!isSourseTapped) sourseLable.Text = datalines[ko - 1].Substring(start + 6, nameLeng - 6 - start - 7); else aimLable.Text = datalines[ko - 1].Substring(start + 6, nameLeng - 6 - start - 7); break; } } await myDB.DeleteAsync(); } catch { MessageDialog dialog = new MessageDialog("Мы не смогли обнаружить ничего рядом с данной меткой. Однако вы все равно можете попробовать построить маршрут, используя её.", "Ничего не найдено!"); } }
/// <summary> /// Downloads a file from the specified address and returns the file. /// </summary> /// <param name="fileUri">The URI of the file.</param> /// <param name="folder">The folder to save the file to.</param> /// <param name="fileName">The file name to save the file as.</param> /// <param name="option"> /// A value that indicates what to do /// if the filename already exists in the current folder. /// </param> /// <remarks> /// If no file name is given - the method will try to find /// the suggested file name in the HTTP response /// based on the Content-Disposition HTTP header. /// </remarks> /// <returns></returns> public async static Task<StorageFile> SaveAsync( Uri fileUri, StorageFolder folder = null, string fileName = null, NameCollisionOption option = NameCollisionOption.GenerateUniqueName) { if (folder == null) { folder = ApplicationData.Current.LocalFolder; } var file = await folder.CreateTempFileAsync(); var downloader = new BackgroundDownloader(); var download = downloader.CreateDownload( fileUri, file); var res = await download.StartAsync(); if (string.IsNullOrEmpty(fileName)) { // Use temp file name by default fileName = file.Name; // Try to find a suggested file name in the http response headers // and rename the temp file before returning if the name is found. var info = res.GetResponseInformation(); if (info.Headers.ContainsKey("Content-Disposition")) { var cd = info.Headers["Content-Disposition"]; var regEx = new Regex("filename=\"(?<fileNameGroup>.+?)\""); var match = regEx.Match(cd); if (match.Success) { fileName = match.Groups["fileNameGroup"].Value; await file.RenameAsync(fileName, option); return file; } } } await file.RenameAsync(fileName, option); return file; }
public async void Download() { FolderPicker folderPicker = new FolderPicker(); folderPicker.SuggestedStartLocation = PickerLocationId.Downloads; folderPicker.ViewMode = PickerViewMode.Thumbnail; folderPicker.FileTypeFilter.Add("*"); StorageFolder folder = await folderPicker.PickSingleFolderAsync(); if (folder != null) { StorageFile file = await folder.CreateFileAsync("Unplash-" + rootObject.user.name + ".jpg", CreationCollisionOption.GenerateUniqueName); //Uri durl = new Uri(rootObject.links.download); //downloadOperation = backgroundDownloader.CreateDownload(durl, file); Uri durl; int getIndex = MainPage.GetLinkwithInt; switch (getIndex) { case 0: durl = new Uri(rootObject.urls.small); downloadOperation = backgroundDownloader.CreateDownload(durl, file); break; case 1: durl = new Uri(rootObject.urls.full); downloadOperation = backgroundDownloader.CreateDownload(durl, file); break; case 2: durl = new Uri(rootObject.urls.raw); downloadOperation = backgroundDownloader.CreateDownload(durl, file); break; } Progress <DownloadOperation> progress = new Progress <DownloadOperation>(progressChanged); cancellationToken = new CancellationTokenSource(); try { //Statustext.Text = "Initial vizing..."; Statusring.IsActive = true; await downloadOperation.StartAsync().AsTask(cancellationToken.Token, progress); } catch (TaskCanceledException) { downloadOperation.ResultFile.DeleteAsync(); downloadOperation = null; } } }
// Click on find-adress button // Forming omniBox private async void button5_Click(object sender, RoutedEventArgs e) { string address = "http://geocode-maps.yandex.ru/1.x/?geocode=" + textBox.Text; StorageFile myDB; try { listBox.Visibility = Visibility.Visible; controlsBG2.Visibility = Visibility.Visible; controlsBG.Visibility = Visibility.Collapsed; listBox.Items.Clear(); StorageFile tempFile2 = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("multi", 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"); // Read the data myDB = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("multi"); var alldata = await Windows.Storage.FileIO.ReadLinesAsync(myDB); datalines = new string[alldata.Count]; int ko = 0; // counter int start; // first no-hashtag sybol in string foreach (var line in alldata) { datalines[ko] = line.ToString(); ko++; if ((start = datalines[ko - 1].IndexOf("<text>")) != -1) { // forming omniBox int nameLeng = datalines[ko - 1].Length; listBox.Items.Add(datalines[ko - 1].Substring(start + 6, nameLeng - 6 - start - 7)); } } await myDB.DeleteAsync(); } catch (Exception) { MessageDialog dialog = new MessageDialog("Ошибка при поиске Вашего запроса. Очистите карту и попробуйте построить маршрут снова.", "Ошибка поиска #007101"); } }
private static async void DoDownload() { try { Uri uri = new Uri("http://kiewic.com"); IStorageFile resultFile = await KnownFolders.PicturesLibrary.CreateFileAsync("blah.html", CreationCollisionOption.GenerateUniqueName); BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(uri, resultFile); await download.StartAsync(); Debug.WriteLine(download.Progress.Status); } catch (Exception ex) { Debug.WriteLine(ex); } }
private async void Button_Click(object sender, RoutedEventArgs e) { string serverAddressField = "http://distribution.bbb3d.renderfarming.net//video/png/00_00/0001.png"; Uri source = new Uri(serverAddressField); string destination = "TEST.png"; StorageFile destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync( destination, CreationCollisionOption.GenerateUniqueName); BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(source, destinationFile); Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress); // await download.StartAsync(); await download.StartAsync().AsTask(cts.Token,progressCallback); }
private async void doLoadBG() { try { System.Xml.Linq.XDocument xmlDoc = XDocument.Load("http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=en-US"); IEnumerable<string> strTest = from node in xmlDoc.Descendants("url") select node.Value; string strURL = "http://www.bing.com" + strTest.First(); Uri source = new Uri(strURL); StorageFile destinationFile; try { destinationFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("raindropBG.jpg", CreationCollisionOption.ReplaceExisting); } catch (FileNotFoundException ex) { return; } BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(source, destinationFile); await download.StartAsync(); ResponseInformation response = download.GetResponseInformation(); Uri imageUri; BitmapImage image = null; if (Uri.TryCreate(destinationFile.Path, UriKind.RelativeOrAbsolute, out imageUri)) { image = new BitmapImage(imageUri); } imgBrush.ImageSource = image; } catch { // } }
/// <summary> /// Overrides the base execute logic to use the background downloader to download the file. /// </summary> protected async override void OnExecute() { var loginResult = await this.LiveClient.Session.AuthClient.GetLoginStatusAsync(); if (loginResult.Error != null) { this.taskCompletionSource.SetException(loginResult.Error); return; } else { var downloader = new BackgroundDownloader(); downloader.SetRequestHeader( ApiOperation.AuthorizationHeader, AuthConstants.BearerTokenType + " " + loginResult.Session.AccessToken); downloader.SetRequestHeader(ApiOperation.LibraryHeader, Platform.GetLibraryHeaderValue()); downloader.Group = LiveConnectClient.LiveSDKDownloadGroup; this.downloadOp = downloader.CreateDownload(this.Url, this.OutputFile); this.taskCompletionSource.SetResult(new LiveDownloadOperation(downloadOp)); } }
private async void pickerSelectionChanged(PickerFileMessage obj) { if (obj.Selected) { Uri uri = new Uri(obj.TargetUrl); string filename = Path.GetFileName(uri.LocalPath); var file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); var downloader = new BackgroundDownloader(); var download = downloader.CreateDownload( uri, file); var res = await download.StartAsync(); _fileOpenPickerUI.AddFile(obj.TargetUrl, file); } else if (_fileOpenPickerUI.ContainsFile(obj.TargetUrl)) { _fileOpenPickerUI.RemoveFile(obj.TargetUrl); } }
// Loading and reading big file private async void button3_Click(object sender, RoutedEventArgs e) { if (OwnSemaphoreBtn3 == true) { OwnSemaphoreBtn3 = false; textBlock1.Text = "загрузка"; StorageFile myDB; try { string address = @"http://artmordent.ru/cheataxi/multiplylines.cr"; StorageFile tempFile2 = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("multi", 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("multi"); // Read the data var alldata = await Windows.Storage.FileIO.ReadLinesAsync(myDB); string[] datalines = new string[alldata.Count]; Int32 ko = 0; foreach (var line in alldata) { datalines[ko] = line.ToString(); ko++; log1.Text += line.ToString() + "\r\n"; } await myDB.DeleteAsync(); } catch (Exception) { textBlock1.Text = "Download Error"; } OwnSemaphoreBtn3 = true; } }
private async Task GetImageUpdated(string url, string fileName, string folderName) { try { Uri source = new Uri(url); string destination = fileName; StorageFolder folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists); StorageFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists); BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(source, file); await HandleDownloadAsync(download); } catch (Exception ex) { Debug.WriteLine("------------------------" + Environment.NewLine + "Download Error" + Environment.NewLine + "Filename : " + fileName + Environment.NewLine + "Folder : " + folderName + Environment.NewLine + "------------------------", ex); } }
public async Task StartDownlodAsync() { try { _cts = new CancellationTokenSource(); var source = DownloadUrl; var fileName = GetFileName(); await EnsureRootFolderExistsAsync(); var destinationFile = await _rootFolder.CreateFileAsync( fileName, CreationCollisionOption.OpenIfExists); LocalFileUrl = new Uri(destinationFile.Path); var downloader = new BackgroundDownloader(); //downloader.SuccessToastNotification =this.GetSuccessToastTemplate(); //downloader.FailureToastNotification = new ToastNotification(new XmlDocument()); _download = downloader.CreateDownload(source, destinationFile); Id = _download.Guid; // Attach progress and completion handlers. await HandleDownloadAsync(true); } catch (Exception ex) { var a = 5; } }
private async void DownloadFile() { try { var source = new Uri(SelectedMusic.file, UriKind.Absolute); var destinationFile = await KnownFolders.MusicLibrary.CreateFileAsync(SelectedMusic.title + ".mp3", CreationCollisionOption.ReplaceExisting); var downloader = new BackgroundDownloader(); var download = downloader.CreateDownload(source, destinationFile); await download.StartAsync().AsTask(new CancellationToken(), new Progress<DownloadOperation>()); } catch (Exception e) { new MessageDialog(loader.GetString("ErrorDowload")).ShowAsync(); } new MessageDialog(loader.GetString("DownloadOk")).ShowAsync(); }
public override async Task<bool> CopyFromRemote(string url, string toPath) { try { Uri downloadUri; if (!Uri.TryCreate(url, UriKind.Absolute, out downloadUri)) return false; var folder = await CreateFolderTree(new DirectoryData(toPath)); var createdFile = await folder.CreateFileAsync(Path.GetFileName(toPath), CreationCollisionOption.ReplaceExisting); var downloader = new BackgroundDownloader(); var downloadOperation = downloader.CreateDownload(downloadUri, createdFile); await downloadOperation.StartAsync(); var responseInfo = downloadOperation.GetResponseInformation(); return responseInfo.StatusCode == 200; } catch (Exception ex) { WindowsPhoneUtils.Log(ex.Message); return false; } }