• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# BackgroundTransfer.BackgroundDownloader类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中Windows.Networking.BackgroundTransfer.BackgroundDownloader的典型用法代码示例。如果您正苦于以下问题:C# BackgroundDownloader类的具体用法?C# BackgroundDownloader怎么用?C# BackgroundDownloader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



BackgroundDownloader类属于Windows.Networking.BackgroundTransfer命名空间,在下文中一共展示了BackgroundDownloader类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: SaveFileFromUriAsync

        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;
        }
开发者ID:Synergex,项目名称:Baconography,代码行数:27,代码来源:ImagesService.cs


示例2: getInfo

        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("Ошибка загрузки информации. Проверьте ваше соединение или попробуйте позже.", "Ошибка загрузки");
            }
        }
开发者ID:Voropash,项目名称:CheaTaxiWin10,代码行数:33,代码来源:info.xaml.cs


示例3: DownloadPodcastEpisodeAsync

        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;
            }
        }
开发者ID:robertiagar,项目名称:podcastr,代码行数:32,代码来源:PodcastDownloaderService.cs


示例4: DownLoadSingleFileAsync

        /// <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;

            }
        }
开发者ID:Neilxzn,项目名称:NeilSoft.UWP,代码行数:34,代码来源:DownLoadHelper.cs


示例5: RequestImage

        //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);
        }
开发者ID:rvrtex,项目名称:mJohnsonYouMaps,代码行数:36,代码来源:ImageDownloader.cs


示例6: Download

		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 ;
		}
开发者ID:pikax,项目名称:papreader,代码行数:26,代码来源:DownloadHelper.cs


示例7: Button_Click

		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);
			;
		}
开发者ID:robledop,项目名称:Demos-20485,代码行数:30,代码来源:MainPage.xaml.cs


示例8: Create

 public static async Task<DownloadItem> Create(BackgroundDownloader b, string url)
 {
     DownloadItem item = new DownloadItem();
     item.Downloader = b;
     item.Url = url;
     await item.Construct();   
     return item;
 }
开发者ID:akshay2000,项目名称:MonocleGiraffe,代码行数:8,代码来源:DownloadItem.cs


示例9: StartDownload

        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);
        }
开发者ID:yazdipour,项目名称:Subtitler-Old,代码行数:57,代码来源:DlDialog.xaml.cs


示例10: download

        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();
        }
开发者ID:kisorbiswal,项目名称:accounter,代码行数:10,代码来源:Downloader.cs


示例11: DownloadClick

 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);
 }
开发者ID:vulcanlee,项目名称:Windows8Lab,代码行数:11,代码来源:MainPage.xaml.cs


示例12: DownloadFileAsync

        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;
                }
            }

        }
开发者ID:Solocast,项目名称:solocast-clients,代码行数:54,代码来源:FileDownloadService.cs


示例13: StartDownload

        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);
        }
开发者ID:yazdipour,项目名称:Subtitler-Old,代码行数:53,代码来源:Downloader.cs


示例14: GetAsync

        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);
        }
开发者ID:radu-ungureanu,项目名称:TrenCalator,代码行数:12,代码来源:DownloadClient.cs


示例15: Start

 /// <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();
     }
 }
开发者ID:yszhangyh,项目名称:KuGouMusic-UWP,代码行数:57,代码来源:BackgroundDownload.cs


示例16: CreateBackgroundDownloader

        public static BackgroundDownloader CreateBackgroundDownloader()
        {
            BackgroundTransferCompletionGroup completionGroup = new BackgroundTransferCompletionGroup();

            BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
            builder.TaskEntryPoint = "Tasks.CompletionGroupTask";
            builder.SetTrigger(completionGroup.Trigger);

            BackgroundTaskRegistration taskRegistration = builder.Register();

            BackgroundDownloader downloader = new BackgroundDownloader(completionGroup);

            return downloader;
        }
开发者ID:RasmusTG,项目名称:Windows-universal-samples,代码行数:14,代码来源:CompletionGroupTask.cs


示例17: Button_Click_1

        // 非同期ダウンロードする
        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);
        }
开发者ID:runceel,项目名称:winstoreapprecipe,代码行数:16,代码来源:MainPage.xaml.cs


示例18: SaveAsync

        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;
        }
开发者ID:Cherlie,项目名称:ZhiHu-App-for-WP8.1,代码行数:15,代码来源:DownloadImage.cs


示例19: SaveAsync

        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();
        }
开发者ID:kusl,项目名称:vlcwinrt,代码行数:15,代码来源:DownloadAndSaveHelper.cs


示例20: getPlaceFromCoordinates

        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("Мы не смогли обнаружить ничего рядом с данной меткой. Однако вы все равно можете попробовать построить маршрут, используя её.", "Ничего не найдено!");
            }
        }
开发者ID:Voropash,项目名称:CheaTaxiWin10,代码行数:48,代码来源:getplacefromtap.cs



注:本文中的Windows.Networking.BackgroundTransfer.BackgroundDownloader类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Sockets.DatagramSocket类代码示例发布时间:2022-05-26
下一篇:
C# Networking.HostName类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap