Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 16, 2021 08:46 am GMT

Download file using HttpClient wrapper asynchronously.

HttpClient is a simple and robust wrapper to send and receive HTTP requests. It's an awesome alternative to the legacy HTTP client .NET api. I like HttpClient the best. It's free, efficient and especially easy to use. You can send HTTP requests and then receive data back only with a couple of code lines.

For instance:
A function to download file with a provided uri and output path.

public static class HttpHelper{   private static readonly HttpClient _httpClient = new HttpClient();   public static async void DownloadFileAsync(string uri        , string outputPath)   {      Uri uriResult;      if (!Uri.TryCreate(uri, UriKind.Absolute, out uriResult))         throw new InvalidOperationException("URI is invalid.");      if (!File.Exists(outputPath))         throw new FileNotFoundException("File not found."            , nameof(outputPath));      byte[] fileBytes = await _httpClient.GetByteArrayAsync(uri);      File.WriteAllBytes(outputPath, fileBytes);   }}

Hope you enjoy this post.

Happy coding :)


Original Link: https://dev.to/1001binary/download-file-using-httpclient-wrapper-asynchronously-1p6

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To