public async Task LoadFile() { using (WebClient webClient = new WebClient()) { this.data = await webClient.DownloadDataTaskAsync(this.SourceFile); } using (MemoryStream stream = new MemoryStream()) { // WAV HEADER // chunk type "RIFF" (0x52494646) // RIFF type "WAVE" (0x57415645) int chunkType = BitConverter.ToInt32(this.data, 0); if (chunkType != 0x46464952) { throw new InvalidDataException("Invalid WAV file"); } UInt32 size = BitConverter.ToUInt32(this.data, 4); int riffType = BitConverter.ToInt32(this.data, 8); if (riffType != 0x45564157) { throw new InvalidDataException("Invalid WAV file"); } // Read WAV chunks int chunkStartIndex = 12; while (chunkStartIndex < (size - 8)) { chunkType = BitConverter.ToInt32(this.data, chunkStartIndex); char[] ct = ASCIIEncoding.ASCII.GetChars(this.data, chunkStartIndex, 4); int chunkSize = (int)BitConverter.ToUInt32(this.data, chunkStartIndex + 4); // chunk type "data" (0x61746164) if (chunkType == 0x61746164) { stream.Write(this.data, chunkStartIndex + 8, chunkSize - 8); } chunkStartIndex += 8 + chunkSize; } this.data = stream.ToArray(); } }
public async Task <IActionResult> PostFromUrl([Url] string url, string fileName) { if (string.IsNullOrEmpty(url)) { return(BadRequest()); } Uri uri = new Uri(url); try { using var client = new WebClient(); var imageBytes = await client.DownloadDataTaskAsync(uri); Models.FileInformation imageInfo = new Models.FileInformation() { fileName = fileName ?? Path.GetFileName(url), data = imageBytes }; await _imageService.FileCheck(imageInfo); ImageDbModel model = new ImageDbModel() { FileName = imageInfo.fileName, AddedDate = DateTime.Now, ImageData = imageBytes, PreviewData = resizer.Resize(imageBytes), }; await _imageService.Save(model, _dbContext); return(Ok()); } catch (ArgumentException ex) { return(BadRequest(ex.Message)); } catch (Exception ex) { _logger.LogError(ex.Message); return(StatusCode(500)); } }
public async Task <byte[]> DownloadAsync(Version version) { byte[] vRet = null; if (!m_blnIsDownloading) { m_blnIsDownloading = true; //Required for SSL connections ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; using (m_webClient = new WebClient()) { vRet = await m_webClient.DownloadDataTaskAsync(GetDownloadUri(version)); } m_blnIsDownloading = false; } return(vRet); }
private static async Task DownloadAsync() { //var l = new List<int>(); using (var wc = new WebClient()) { //End of Main Thread (return Task) byte[] image = await wc.DownloadDataTaskAsync(new Uri(URL)); //using (var fs = File.OpenWrite($"Sync-{DateTime.Now:HH_mm_ss}.jpg")) using (var fs = new FileStream($"Async-{DateTime.Now:HH_mm_ss}.jpg", FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.Asynchronous)) { // End of Thread Pool Execution (scheduled by the TaskScheduler) await fs.WriteAsync(image, 0, image.Length); } } Console.WriteLine("Async Ready"); // End of Thread Pool Execution (scheduled by the TaskScheduler) // Task state change to completed }
} // end method searchButton_Click // display selected image private async void imagesListBox_SelectedIndexChanged( object sender, EventArgs e) { if (imagesListBox.SelectedItem != null) { string selectedURL = (( FlickrResult )imagesListBox.SelectedItem).URL; // use WebClient to get selected image's bytes asynchronously //Create a WebClient object WebClient imageClient = new WebClient(); //Invoke the the WeClient DownloadDataTaskAsync method to get byte array called imageBytes that contains the photo (from selectedURL) and await the results. byte[] imageBytes = await imageClient.DownloadDataTaskAsync(selectedURL); //Create a MemoryStream object from imagesBytes MemoryStream memorySteam = new MemoryStream(imageBytes); //Use the Image class's static FromStream method to create an image from the MemoryStream object and assign the image to the PictureBox's image property //to display the selected photo pictureBox.Image = Image.FromStream(memorySteam); } // end if } // end method imagesListBox_SelectedIndexChanged
async Task <Drawing.Bitmap> DownloadImages(string url, string name) { Drawing.Bitmap imageBitmap = null; try { using (var webClient = new WebClient()) { var imageBytes = await webClient.DownloadDataTaskAsync(url); MemoryStream ms = new MemoryStream(imageBytes); Drawing.Image i = Drawing.Image.FromStream(ms); i.Save(@"C:\snakeImg\" + name + ".png"); } } catch { //Silence is gold. } return(imageBitmap); }
public async Task <IActionResult> Load([FromBody] Dictionary <string, string> jsonObject, CancellationToken cancellationToken) { //Initialize the PDF viewer object with memory cache object PdfRenderer pdfViewer = new PdfRenderer(Cache); MemoryStream stream; using (var client = new WebClient()) { var bookAbsoluteUrl = await _bookService.GetBookFileAbsoluteUrl(jsonObject["document"].ToInt(), cancellationToken); var bookFileBytes = await client.DownloadDataTaskAsync(bookAbsoluteUrl); stream = new MemoryStream(bookFileBytes); } var jsonResult = pdfViewer.Load(stream, jsonObject); return(Content(JsonConvert.SerializeObject(jsonResult))); }
private async Task Load() { try { var webClient = new WebClient(); webClient.DownloadProgressChanged += webClient_DownloadProgressChanged; var bytes = await webClient.DownloadDataTaskAsync(new Uri(_url)); _bitmap = await BitmapFactory.DecodeByteArrayAsync(bytes, 0, bytes.Length); if (Completed != null && _bitmap != null) { Completed(this); } } catch (Exception ex) { Log.Debug("SwiperRenderer", "Exception loading image '{0}' using WebClient '{1}'", _url, ex.ToString()); } }
private async Task <Image <Rgba32> > DownloadImage(string url) { var client = new WebClient(); client.OpenRead(url); var bytesTotal = Convert.ToInt64(client.ResponseHeaders["Content-Length"]); _logger.LogInformation($"Got an image with size {bytesTotal} from url: {url}"); if (bytesTotal < MinImageSize) { client.Dispose(); return(null); } _logger.LogInformation($"Downloading an image from {url}"); var result = await client.DownloadDataTaskAsync(url); client.Dispose(); return(Image.Load(result)); }
public async Task <Dictionary <string, byte[]> > DownloadAsync(string link, params string[] fileNames) { var downloadedFiles = new Dictionary <string, byte[]>(); using (var webClient = new WebClient { BaseAddress = link }) { var index = 1; foreach (var fileName in fileNames) { var content = await webClient.DownloadDataTaskAsync(fileName); downloadedFiles.Add(fileName, content); OnDownloadProgress?.Invoke(this, index++ *100f / fileNames.Length); } return(downloadedFiles); } }
public async Task <float> CreateDownloadTask(string urlToDownload, string fileName, IProgress <float> progessReporter) { byte[] bytes = null; WebClient client = new WebClient(); client.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) => { progessReporter.Report((float)e.ProgressPercentage / 100); }; bytes = await client.DownloadDataTaskAsync(new Uri(urlToDownload)); string downloadPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads); string localPath = Path.Combine(downloadPath, fileName); FileStream fs = new FileStream(localPath, FileMode.OpenOrCreate); await fs.WriteAsync(bytes, 0, bytes.Length); fs.Close(); return(1); }
private async void GetMinerFee() { using (WebClient client = new WebClient()) { client.Headers.Add(HttpRequestHeader.ContentType, "application/json"); string responseString; try { JObject response = null; var Uriurl = new Uri($"https://bitcoinfees.21.co/api/v1/fees/recommended"); var responseBytes = await client.DownloadDataTaskAsync(Uriurl); responseString = Encoding.UTF8.GetString(responseBytes); response = JObject.Parse(responseString); } catch (WebException e) { } } }
//todo: move convert logic to service public async Task <string> audioToTextOnlineConverter(string url) { try { var uri = new Uri(url); _logger.Log(NLog.LogLevel.Info, uri); using (WebClient client = new WebClient()) { var flacUrl = await onlineConverterService.convertMp3ToFlac(url); byte[] audioFlac = await client.DownloadDataTaskAsync(uri); return(await googleService.flacToText(audioFlac)); } } catch (Exception ex) { _logger.Log(NLog.LogLevel.Error, ex, "audioToText Error"); return(null); } }
//todo: move to separate audio/google service public async Task <string> audioToText(string url) { try { var uri = new Uri(url); _logger.Log(NLog.LogLevel.Info, uri); using (WebClient client = new WebClient()) { //get audio byte[] audioMP3 = await client.DownloadDataTaskAsync(uri); byte[] audioWav = VkontakteBot.Services.AudioService.decodeMP3ToWavMono(audioMP3); return(await googleService.wavToText(audioWav)); } } catch (Exception ex) { _logger.Log(NLog.LogLevel.Error, ex, "audioToText Error"); return(null); } }
// 未完成 /// <summary> /// 根据下载路径下载文件 /// </summary> /// <param name="uris">下载路基集合</param> /// <returns></returns> private async Task <int> SumPageSizesAsync(IList <Uri> uris) { int total = 0; string sss = ""; foreach (var uri in uris) { sss = string.Format("Found {0} bytes...", total); using (WebClient client = new WebClient()) { //var data =await client.DownloadFileAsync(uri, total.ToString()); await client.DownloadDataTaskAsync(uri); } await new WebClient().DownloadFileTaskAsync(uri, total.ToString()); var data = await new WebClient().DownloadDataTaskAsync(uri); total += data.Length; } sss = string.Format("Found {0} bytes total", total); //return await Task.FromResult(); return(total); }
public static async Task DownloadDataAsync(Uri uri) { using (WebClient client = new WebClient()) { Console.WriteLine($"Downloading {uri.AbsoluteUri}"); byte[] bytes; try { bytes = await client.DownloadDataTaskAsync(uri); } catch (WebException we) { Console.WriteLine(we); return; } string page = Encoding.UTF8.GetString(bytes); Console.WriteLine(page); } }
public static async Task <BitmapImage> GetPicAsync(string url) { try { //HTTP下载图片 WebClient wc = new WebClient(); using (var ms = new MemoryStream(await wc.DownloadDataTaskAsync(new Uri(url)))) { var image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.StreamSource = ms; image.EndInit(); return(image); } } catch { return(null); } }
/// <summary> /// Возвращает указанную веб страницу /// </summary> /// <param name="uri"></param> /// <returns></returns> async Task <string> GetPage(string uri) { var webClient = new WebClient(); byte[] data; try { data = await webClient.DownloadDataTaskAsync(new Uri(uri)); } catch (WebException ex) { _logger.LogError(ex, "Указан неврный адрес или произошла другая сетевая ошибка"); return(null); } if (data != null) { return(Encoding.UTF8.GetString(data)); } return(null); }
private static async Task <string> StoreEventImageInBlobStorage( DownloadEventImageModel eventImageModel, Binder binder, ILogger log) { Uri uri = new Uri(eventImageModel.ImageUrl); var filename = Path.GetFileName(uri.LocalPath); var downloadLocationForEventImage = $"eventimages/{eventImageModel.Id}/{filename}"; using var blobBinding = await binder.BindAsync <Stream>( new Attribute[] { new BlobAttribute(downloadLocationForEventImage, FileAccess.Write), new StorageAccountAttribute("StorageAccountConnectionString") }); var webClient = new WebClient(); var imageBytes = await webClient.DownloadDataTaskAsync(uri); log.LogInformation($"Writing event image for CFP `{eventImageModel.Id}` to location `{downloadLocationForEventImage}`."); await blobBinding.WriteAsync(imageBytes, 0, imageBytes.Length); return(downloadLocationForEventImage); }
/// <summary> /// Download a file as a byte array async using a GetFileResponse. /// </summary> public static async Task <byte[]> DownloadFileAsync(this TeleBot bot, GetFileResponse getFileResponse) { bot.Log.Info(nameof(DownloadFileAsync)); if (string.IsNullOrEmpty(getFileResponse?.Result?.FilePath)) { return(null); } using (var client = new WebClient()) { try { return(await client.DownloadDataTaskAsync($"{TeleBot.ApiUrl}/file/bot{bot.ApiToken}/{getFileResponse.Result.FilePath}")); } catch { return(null); } } }
private async Task <byte[]> DownloadWebContentAsByteArrayAsync(string rawUrl, string token) { try { using (var webClient = new WebClient()) { if (!token.IsNullOrWhiteSpace()) { webClient.Headers.Add("Authorization", "token " + token); } return(await webClient.DownloadDataTaskAsync(new Uri(rawUrl))); } } catch (Exception ex) { //TODO: Only handle when resource is really not available Logger.LogWarning(ex.Message, ex); throw new ResourceNotFoundException(rawUrl); } }
public async static Task <byte[]> DownloadImage(string imageUrl) { byte[] img = null; try { using (WebClient client = new WebClient()) { img = await client.DownloadDataTaskAsync(imageUrl); } } catch (HttpListenerException ex) { Console.WriteLine("Error accessing " + imageUrl + " - " + ex.Message); } catch (Exception ex) { Console.WriteLine("Error accessing " + imageUrl + " - " + ex.Message); } return(img); }
public async Task <T> GetDataAsync( string url, Proxy proxy = null) { WebClient web = new WebClient(); if (proxy != null) { web.Proxy = new WebProxy(proxy.Address); web.Proxy.Credentials = new NetworkCredential( proxy.Username, proxy.Password ); } var data_byte = await web.DownloadDataTaskAsync(url); var data_str = System.Text.Encoding.UTF8.GetString(data_byte); return(JsonConvert.DeserializeObject <T>(data_str)); }
private async Task <string> DownloadPowerShellScript() { string text = string.Empty; try { WebClient client = new WebClient(); Task <byte[]> task = client.DownloadDataTaskAsync(string.Format("{0}/{1}/{2}", objectEndPoint, bucket, textBoxPowerShellScriptName.Text)); var contents = await task; text = Encoding.Default.GetString(contents); if (text.Length < 1) { new Exception("remote powershell script error"); } } catch (Exception) { throw; } return(text); }
private static async Task <string> StoreEventImageInBlobStorage( Binder binder, TraceWriter log, Models.DownloadEventImage eventImageModel) { Uri uri = new Uri(eventImageModel.ImageUrl); var filename = Path.GetFileName(uri.LocalPath); var downloadLocationForEventImage = $"eventimages/{eventImageModel.Id}/{filename}"; using (var blobBinding = await binder.BindAsync <Stream>( new BlobAttribute(downloadLocationForEventImage, FileAccess.Write))) { var webClient = new WebClient(); var imageBytes = await webClient.DownloadDataTaskAsync(uri); log.Verbose($"Writing event image for CFP `{eventImageModel.Id}` to location `{downloadLocationForEventImage}`."); await blobBinding.WriteAsync(imageBytes, 0, imageBytes.Length); return(downloadLocationForEventImage); } }
public async Task <T> Get <T>(string url, Action doneCallback = null) { var client = new WebClient(); client.Headers.Add("Content-Type", "application/json"); //client.Headers.Add("Authorization", "Bearer " + authenticationToken.Token); var response = client.DownloadDataTaskAsync(url); if (doneCallback != null) { client.DownloadDataCompleted += (s, e) => { doneCallback(); }; } var stream = new MemoryStream(await response); var jsonSerializer = new DataContractJsonSerializer(typeof(T)); object objResponse = jsonSerializer.ReadObject(stream); return((T)objResponse); }
/// <summary> /// 异步获取歌曲详细信息API /// </summary> /// <param name="ids">歌曲id</param> /// <returns>从服务器上接收到的数据</returns> private async static Task <String> GetDetialApiAsync(String ids) { using (WebClient client = new WebClient()) { // 必要的HTTP头 client.Headers.Add("Cookie", "appver=1.5.2;"); client.Headers.Add("Referer", "http://music.163.com/"); client.Headers.Add("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36"); String url = "http://music.163.com/api/song/detail/"; client.QueryString.Add("ids", ids); client.QueryString.Add("csrf_token", ""); try { var responsebytes = await client.DownloadDataTaskAsync(url); return(Encoding.UTF8.GetString(responsebytes)); } catch (WebException e) { throw new WebException("No Internet Exception", e); } } }
public static async Task <string> GetPicBase64Async(string url) { try { //HTTP下载图片 WebClient wc = new WebClient(); using (var ms = new MemoryStream(await wc.DownloadDataTaskAsync(new Uri(url)))) { byte[] arr = new byte[ms.Length]; ms.Position = 0; ms.Read(arr, 0, (int)ms.Length); ms.Close(); string base64 = Convert.ToBase64String(arr); return(base64); } } catch { return(null); } }
/// <summary> /// Gets the favicon of the currently loaded webpage. /// </summary> public static async Task <Icon> GetFavIconAsync(Uri uri) { string url = $@"http://{uri.Host}/favicon.ico"; try { using (var webClient = new WebClient()) { byte[] data = await webClient.DownloadDataTaskAsync(url); var memStream = new MemoryStream(data); var icon = new Icon(memStream); memStream.Close(); return(icon); } } catch { return(null); } }
/// <summary> /// Share a file from a remote resource on compatible services /// </summary> /// <param name="fileUri">uri to external file</param> /// <param name="fileName">name of the file</param> /// <param name="title">Title of popup on share (not included in message)</param> /// <returns>awaitable bool</returns> public async Task ShareRemoteFile(string fileUri, string fileName, string title = "") { try { using (var webClient = new WebClient()) { var uri = new System.Uri(fileUri); var bytes = await webClient.DownloadDataTaskAsync(uri); var filePath = WriteFile(fileName, bytes); ShareLocalFile(filePath, title); } } catch (Exception ex) { if (ex != null && !string.IsNullOrWhiteSpace(ex.Message)) { Console.WriteLine("Plugin.ShareFile: ShareRemoteFile Exception: {0}", ex.Message); } } }
protected override Task<byte[]> DownloadDataAsync(WebClient wc, string address) => wc.DownloadDataTaskAsync(address);
public static async Task ConcurrentOperations_Throw() { await LoopbackServer.CreateServerAsync((server, url) => { var wc = new WebClient(); Task ignored = wc.DownloadDataTaskAsync(url); // won't complete Assert.Throws<NotSupportedException>(() => { wc.DownloadData(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadDataAsync(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadDataTaskAsync(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadString(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadStringAsync(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadStringTaskAsync(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadFile(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadFileAsync(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadFileTaskAsync(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadData(url, new byte[42]); }); Assert.Throws<NotSupportedException>(() => { wc.UploadDataAsync(url, new byte[42]); }); Assert.Throws<NotSupportedException>(() => { wc.UploadDataTaskAsync(url, new byte[42]); }); Assert.Throws<NotSupportedException>(() => { wc.UploadString(url, "42"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadStringAsync(url, "42"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadStringTaskAsync(url, "42"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadFile(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadFileAsync(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadFileTaskAsync(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadValues(url, new NameValueCollection()); }); Assert.Throws<NotSupportedException>(() => { wc.UploadValuesAsync(url, new NameValueCollection()); }); Assert.Throws<NotSupportedException>(() => { wc.UploadValuesTaskAsync(url, new NameValueCollection()); }); return Task.CompletedTask; }); }
public static void DownloadData_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadData((string)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadData((Uri)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadDataAsync((Uri)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadDataAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadDataTaskAsync((string)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadDataTaskAsync((Uri)null); }); }