当前位置: 首页>>代码示例>>C#>>正文


C# WebClient.OpenReadTaskAsync方法代码示例

本文整理汇总了C#中System.Net.WebClient.OpenReadTaskAsync方法的典型用法代码示例。如果您正苦于以下问题:C# WebClient.OpenReadTaskAsync方法的具体用法?C# WebClient.OpenReadTaskAsync怎么用?C# WebClient.OpenReadTaskAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.WebClient的用法示例。


在下文中一共展示了WebClient.OpenReadTaskAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetBytes

		async Task<int> GetBytes(string url, CancellationToken cancelToken, IProgress<DownloadBytesProgress> progressIndicator)
		{
			int receivedBytes = 0;
			int totalBytes = -1;
			WebClient client = new WebClient();

			using (var stream = await client.OpenReadTaskAsync(url))
			{
				byte[] buffer = new byte[4096];
				Int32.TryParse(client.ResponseHeaders[HttpResponseHeader.ContentLength], out totalBytes);

				for (;;)
				{
					int len = await stream.ReadAsync(buffer, 0, buffer.Length);
					if (len == 0)
					{
						await Task.Yield();
						break;
					}

					receivedBytes += len;
					cancelToken.ThrowIfCancellationRequested();

					if (progressIndicator != null)
					{
						DownloadBytesProgress args = new DownloadBytesProgress(url, receivedBytes, totalBytes);
						progressIndicator.Report(args);
					}
				}
			}
			return receivedBytes;
		}
开发者ID:CodeSensei,项目名称:mobile-samples,代码行数:32,代码来源:AsyncExtrasController.cs

示例2: CreateDownloadTask

public static async Task<int> CreateDownloadTask(string urlToDownload, IProgress<DownloadBytesProgress> progessReporter)
{
	int receivedBytes = 0;
	int totalBytes = 0;
	WebClient client = new WebClient();

	using (var stream = await client.OpenReadTaskAsync(urlToDownload))
	{
		byte[] buffer = new byte[BufferSize];
		totalBytes = Int32.Parse(client.ResponseHeaders[HttpResponseHeader.ContentLength]);

		for (;;)
		{
			int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
			if (bytesRead == 0)
			{
				await Task.Yield();
				break;
			}

			receivedBytes += bytesRead;
			if (progessReporter != null)
			{
				DownloadBytesProgress args = new DownloadBytesProgress(urlToDownload, receivedBytes, totalBytes);
				progessReporter.Report(args);
			}
		}
	}
	return receivedBytes;
}
开发者ID:eduardoguilarducci,项目名称:recipes,代码行数:30,代码来源:DownloadHelper.cs

示例3: GetImageList

        private Task<IEnumerable<string>> GetImageList(string artistName, CancellationToken token)
        {
            var replacedSpaces = artistName.Replace(" ", "_");
            var siteUri = new Uri("http://htbackdrops.com/api/" + ApiKey + "/searchXML?keywords=" + replacedSpaces + "&limit=7");
            var client = new WebClient();

            return client
                .OpenReadTaskAsync(siteUri)
                .ContinueWith(readTask =>
                {
                    if (readTask.IsFaulted)
                    {
                        Trace.WriteLine(readTask.Exception);
                        return new string[0];
                    }

                    var doc = new XmlDocument();
                    doc.Load(readTask.Result);

                    XmlNodeList nodelist = doc.SelectNodes("/search/images/image/id");

                    if (nodelist == null || nodelist.Count == 0)
                    {
                        return new string[0];
                    }

                    return nodelist
                        .OfType<XmlNode>()
                        .Select(node => node.InnerText)
                        .Select(imageId => "http://htbackdrops.com/api/" + ApiKey + "/download/" + imageId + "/intermediate");
                }, token);
        }
开发者ID:torshy,项目名称:TRock.Party,代码行数:32,代码来源:BackdropController.cs

示例4: UpdateListFromRemote

        public async Task UpdateListFromRemote()
        {
            var s = StorageHelper.ReadFromLocalCache(ConfigFileName, CacheDays);
            if (s != null)
            {
                s.Dispose();
                return;
            }

            var client = new WebClient();
            try
            {
                s = await client.OpenReadTaskAsync(RemoteFilePath);
                Debug.WriteLine("Update server list from remote");
                UpdateList(s);

                RefreshList();

                using (s)
                {
                    using (var reader = new StreamReader(s))
                    {
                        s.Seek(0, SeekOrigin.Begin);
                        StorageHelper.WriteToLocalCache(ConfigFileName, reader.ReadToEnd());
                    }
                }
            }
            catch (Exception) { }
        }
开发者ID:5nophilwu,项目名称:S1Nyan,代码行数:29,代码来源:RemoteConfigModelBase.cs

示例5: GetAsStreamAsync

 public Task<Stream> GetAsStreamAsync()
 {
     using (var webClient = new WebClient())
     {
         return webClient.OpenReadTaskAsync(_url);
     }
 }
开发者ID:Bomret,项目名称:Sourcery,代码行数:7,代码来源:UrlSource.cs

示例6: ReadStreamAsync

 static async Task<string> ReadStreamAsync(string url)
 {
     using (var client = new WebClient())
     using (var reader = new StreamReader(await client.OpenReadTaskAsync(url)))
     {
         return await reader.ReadToEndAsync();
     }
 }
开发者ID:shayim,项目名称:Programming-DotNet,代码行数:8,代码来源:Program.cs

示例7: LoadDataAsync

        /// <summary>
        /// Load data from flickr
        /// </summary>
        /// <param name="tags"></param>
        /// <returns></returns>
        private static async Task<XmlNodeList> LoadDataAsync(string tags)
        {
            var webClient = new WebClient();
            var stream = await
                webClient.OpenReadTaskAsync(
                    new Uri($"http://api.flickr.com/services/feeds/photos_public.gne?tags={tags}"));

            var xdoc = new XmlDocument();//xml doc used for xml parsing
            xdoc.Load(stream);
            var xNodelst = xdoc.GetElementsByTagName("entry");
            return xNodelst;
        }
开发者ID:amigin,项目名称:Flikr-test-assesment,代码行数:17,代码来源:ImagesRepository.cs

示例8: GetPhotoAsync

 public async Task<BitmapSource> GetPhotoAsync(string uri)
 {
     WebClient client = new WebClient();
     Stream stream = await client.OpenReadTaskAsync(uri);
     try
     {
         return PictureDecoder.DecodeJpeg(stream);
     }
     catch (COMException)
     {
         return null;
     }
 }
开发者ID:aTEuCT,项目名称:VkMessenger,代码行数:13,代码来源:VkService.cs

示例9: DownloadTitles

        /// <summary>
        /// Downloads an xml file from AniDB which contains all of the titles for every anime, and their IDs,
        /// and saves it to disk.
        /// </summary>
        /// <param name="titlesFile">The destination file name.</param>
        private async Task DownloadTitles(string titlesFile)
        {
            _logger.Debug("Downloading new AniDB titles file.");

            var client = new WebClient();

            await AniDbSeriesProvider.RequestLimiter.Tick();

            using (var stream = await client.OpenReadTaskAsync(TitlesUrl))
            using (var unzipped = new GZipStream(stream, CompressionMode.Decompress))
            using (var writer = File.Open(titlesFile, FileMode.Create, FileAccess.Write))
            {
                await unzipped.CopyToAsync(writer).ConfigureAwait(false);
            }
        }
开发者ID:mtlott,项目名称:MediaBrowser.Plugins.Anime,代码行数:20,代码来源:AniDbTitleDownloader.cs

示例10: CheckForInternetConnection

 /// <summary>
 /// Check if the internet is available. It connects to google.com
 /// </summary>
 /// <returns>If the connection to google was successful</returns>
 public async static Task<bool> CheckForInternetConnection()
 {
     try
     {
         using (var client = new WebClient { Proxy = null })
         using (await client.OpenReadTaskAsync("http://www.google.com"))
         {
             return true;
         }
     }
     catch
     {
         return false;
     }
 }
开发者ID:WELL-E,项目名称:Hurricane,代码行数:19,代码来源:GeneralHelper.cs

示例11: DownloadFeed

 private async Task<SyndicationFeed> DownloadFeed(string url)
 {
     try
     {
         using (WebClient client = new WebClient())
         {
             var stream = await client.OpenReadTaskAsync(url);
             return SyndicationFeed.Load(XmlReader.Create(stream));
         }
     }
     catch (Exception)
     {
         return new SyndicationFeed();
     }
 }
开发者ID:prashantkhandelwal,项目名称:DotNetFeeder,代码行数:15,代码来源:Feeder.cs

示例12: LoadImageFromUrlAsync

        /// <summary>
        /// Loads an image from an Url asynchronously
        /// </summary>
        /// <param name="location">The location of the image</param>
        /// <returns>A BitmapImage, that can be set as a source</returns>
        public static async Task<ExtendedImage> LoadImageFromUrlAsync(Uri location)
        {
            WebClient client = new WebClient();
            ExtendedImage image = new ExtendedImage();
            Stream source = await client.OpenReadTaskAsync(location);

            if (location.ToString().EndsWith("gif", StringComparison.InvariantCultureIgnoreCase))
            {
                image.SetSource(source);

                TaskCompletionSource<ExtendedImage> imageLoaded = new TaskCompletionSource<ExtendedImage>();

                EventHandler loadingCompleteHandler = new EventHandler((sender, e) =>
                {
                    imageLoaded.SetResult(image);
                });

                EventHandler<UnhandledExceptionEventArgs> loadingFailedHandler = new EventHandler<UnhandledExceptionEventArgs>((sender, e) =>
                {
                    imageLoaded.SetResult(image);
#if DEBUG
                    if (System.Diagnostics.Debugger.IsAttached)
                        System.Diagnostics.Debugger.Break();
#endif
                });



                image.LoadingCompleted += loadingCompleteHandler;
                image.LoadingFailed += loadingFailedHandler;

                image = await imageLoaded.Task;

                //Remove handlers, otherwise the object might be kept in the memory
                image.LoadingCompleted -= loadingCompleteHandler;
                image.LoadingFailed -= loadingFailedHandler;
            }
            else
            {
                BitmapImage bmp = new BitmapImage();
                bmp.SetSource(source);
                WriteableBitmap writeable = new WriteableBitmap(bmp);
                image = ImageExtensions.ToImage(writeable);
            }

            source.Close();
            return image;
        }
开发者ID:TheInterframe,项目名称:SparklrWP-OLD,代码行数:53,代码来源:Helpers.cs

示例13: DownloadFeed

 private async Task<SyndicationFeed> DownloadFeed(string url)
 {
     try
     {
         using (WebClient client = new WebClient())
         {
             var stream = await client.OpenReadTaskAsync(url);
             return SyndicationFeed.Load(XmlReader.Create(stream));
         }
     }
     catch (Exception ex)
     {
         Trace.Warn("Feed Collector", "Couldn't download: " + url, ex);
         return new SyndicationFeed();
     }
 }
开发者ID:AzarinSergey,项目名称:FeedCollector,代码行数:16,代码来源:Default.aspx.cs

示例14: HasConnectionAsync

 public async Task<bool> HasConnectionAsync(string uri)
 {
     try
     {
         Uri theUri;
         Uri.TryCreate(uri, UriKind.RelativeOrAbsolute, out theUri);
         using (var client = new WebClient())
         {
             await client.OpenReadTaskAsync(uri);
         }
     }
     catch
     {
         return false;
     }
     return true;
 }
开发者ID:FerdinandOlivier,项目名称:Warewolf-ESB,代码行数:17,代码来源:NetworkHelper.cs

示例15: LoadFeed

        private async Task<SyndicationFeed> LoadFeed()
        {
            SyndicationFeed feed;

            using (WebClient wc = new WebClient())
            using (Stream stream = await wc.OpenReadTaskAsync(new Uri("http://businessoftech.com/podcast/feed/1")))
            using (XmlReader reader = XmlReader.Create(stream, new XmlReaderSettings
            {
                CheckCharacters = true,
            }))
            {
                feed = SyndicationFeed.Load(reader);
            }

            feed.AttributeExtensions.Add(new XmlQualifiedName("itunes", "http://www.w3.org/2000/xmlns/"), Constants.ItunesNS.NamespaceName);

            return feed;
        }
开发者ID:swegner,项目名称:tbot-rss,代码行数:18,代码来源:RssController.cs


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