.NET Documentation

ReadAsByteArrayAsync Method

public Task<byte[]> ReadAsByteArrayAsync()

Asynchronously reads the HTTP response content as a byte array.

Remarks

This method is used to read the content of an HTTP response as an array of bytes. It is an asynchronous operation, meaning it will not block the calling thread while the data is being read.

The content is read from the underlying stream. After the content is read, the stream will be disposed of.

Examples

The following example demonstrates how to use ReadAsByteArrayAsync to retrieve the content of a web page as bytes.


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

public class Example
{
    public static async Task Main(string[] args)
    {
        using (HttpClient client = new HttpClient())
        {
            try
            {
                HttpResponseMessage response = await client.GetAsync("https://www.example.com");
                response.EnsureSuccessStatusCode(); // Throw an exception if the status code is not 2xx

                byte[] responseBytes = await response.Content.ReadAsByteArrayAsync();

                Console.WriteLine($"Successfully read {responseBytes.Length} bytes.");
                // You can now process the byte array, e.g., convert it to a string
                // string responseString = System.Text.Encoding.UTF8.GetString(responseBytes);
                // Console.WriteLine(responseString);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"Request error: {e.Message}");
            }
        }
    }
}

Exceptions

Exception Type Condition
ObjectDisposedException The associated HttpClient has been disposed.
InvalidOperationException The content has already been read using a different method (e.g., ReadAsStringAsync, ReadAsStreamAsync, or another ReadAsByteArrayAsync).

See Also