本文整理汇总了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;
}
示例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;
}
示例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);
}
示例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) { }
}
示例5: GetAsStreamAsync
public Task<Stream> GetAsStreamAsync()
{
using (var webClient = new WebClient())
{
return webClient.OpenReadTaskAsync(_url);
}
}
示例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();
}
}
示例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;
}
示例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;
}
}
示例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);
}
}
示例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;
}
}
示例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();
}
}
示例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;
}
示例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();
}
}
示例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;
}
示例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;
}