This content originally appeared on DEV Community and was authored by 1001binary
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 :)
This content originally appeared on DEV Community and was authored by 1001binary
1001binary | Sciencx (2021-04-16T08:46:10+00:00) Download file using HttpClient wrapper asynchronously.. Retrieved from https://www.scien.cx/2021/04/16/download-file-using-httpclient-wrapper-asynchronously/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.