Summary

Reads the content of an HTTP response as a binary byte[] array.

Syntax


public Task<byte[]> ReadFromBinaryAsync(CancellationToken cancellationToken = default);
            

Parameters

Returns

Remarks

This method is useful for reading response bodies that are expected to be binary data, such as images, files, or other non-textual content. The entire content of the response is read into memory. If the response content is very large, consider using streaming methods like ReadAsStreamAsync() to avoid excessive memory consumption.

The CancellationToken can be used to cancel the asynchronous operation. If the operation is canceled, an OperationCanceledException will be thrown.

Example

Downloading an image as a byte array


using System;
using System.Net.Http;
using System.Threading.Tasks;

public class Example
{
    public static async Task DownloadImageAsync(string imageUrl)
    {
        using (HttpClient client = new HttpClient())
        {
            try
            {
                HttpResponseMessage response = await client.GetAsync(imageUrl);
                response.EnsureSuccessStatusCode(); // Throw if the status code is not success

                byte[] imageData = await response.Content.ReadFromBinaryAsync();

                Console.WriteLine($"Downloaded {imageData.Length} bytes from {imageUrl}");

                // You can now process the imageData, for example, save it to a file:
                // await System.IO.File.WriteAllBytesAsync("downloaded_image.jpg", imageData);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"Request error: {e.Message}");
            }
            catch (Exception e)
            {
                Console.WriteLine($"An error occurred: {e.Message}");
            }
        }
    }

    // Example usage:
    // public static async Task Main(string[] args)
    // {
    //     await DownloadImageAsync("https://via.placeholder.com/150");
    // }
}
                

See Also